Sign In
Sign In

How to Create and Optimize Docker Images

How to Create and Optimize Docker Images
Hostman Team
Technical writer
Docker
22.01.2025
Reading time: 12 min

In today's environment, most companies actively use the Docker containerization system in their projects, especially when working with microservice applications. Docker allows you to quickly deploy any applications, whether monolithic or cloud-native. Despite the simplicity of working with Docker, it's important to understand some nuances of creating your own images. In this article, we will explore how to work with Docker images and optimize them using two different applications as examples.

Prerequisites

To work with the Docker containerization system, we will need:

  • A cloud server or a virtual machine with any pre-installed Linux distribution. We will be using Ubuntu 22.04.

  • Docker installed. See our installation guide

You can also use a pre-configured image with Docker. To do this, go to the Cloud servers section in your Hostman control panel, click Create server, and select Docker in the Marketplace tab.

Working with Docker Images

Docker images are created by other users and stored in registries—special repositories for images. Registries can be public or private. Public repositories are available to all users without requiring authentication. Private registries, however, can only be accessed by users with appropriate login credentials. Companies widely use private repositories to store their own images during software development.

By default, Docker uses the public registry Docker Hub, which any user can use to publish their own images or download images created by others. When a user runs a command such as docker run, the Docker daemon will, by default, contact its standard registry. If necessary, you can change the registry to another one.

To create custom Docker images, a Dockerfile is used—a text file containing instructions for building an image. These instructions use 18 specially reserved keywords. The most common types of instructions include the following:

  • FROM specifies the base image. Every image starts with a base image. A base image refers to a Linux distribution, such as Ubuntu, Debian, Oracle Linux, Alpine, etc. There are also many images with various pre-installed software, such as Nginx, Grafana, Prometheus, MySQL, and others. However, even when using an image with pre-installed software, some Linux OS distribution will always be specified inside.

  • WORKDIR creates a directory inside the image. Its functionality is similar to the mkdir utility used to create directories in Linux distributions. It can be used multiple times in one image.

  • COPY copies files and directories from the host system into the image. It is used to copy configuration files and application source code files.

  • ADD is similar to the COPY instruction, but in addition to copying files, ADD allows downloading files from remote sources and extracting .tar archives.

  • RUN executes commands inside the image. With RUN, you can perform any actions that a user can perform in a Bash shell, including creating files, installing packages, starting services, etc.

  • CMD specifies the command that will be executed when the container is started.

Example: Creating an Image

As an example, we will create an image with a simple Python program.

  1. Create a project directory and move into it:

mkdir python-calculator && cd python-calculator
  1. Create a file console_calculator.py with the following content:

print("*" * 10, "Calculator", "*" * 10)
print("To exit from program type q")

try:
 while True:
    arithmetic_operators = input("Choose arithmetic operation (+ - * /):\n")
    if arithmetic_operators == "q":
        break
    if arithmetic_operators in ("+", "-", "*", "/"):
        first_number = float(input("First number is:\n"))
        second_number = float(input("Second number is:\n"))
        print("The result is:")
        if arithmetic_operators == "+":
            print("%.2f" % (first_number + second_number))
        elif arithmetic_operators == "-":
            print("%.2f" % (first_number - second_number))
        elif arithmetic_operators == "*":
            print("%.2f" % (first_number * second_number))
        elif arithmetic_operators == "/":
            if second_number != 0:
                print("%.2f" % (first_number / second_number))
            else:
                print("You can't divide by zero!")      
    else:
        print("Invalid symbol!")

except (KeyboardInterrupt, EOFError) as e:
    print(e)
  1. Create a new Dockerfile with the following content:
FROM python:3.10-alpine

WORKDIR /app

COPY console_calculator.py .

CMD ["python3","console_calculator.py"]

For the base image, we will use python:3.10, which is based on a lightweight Linux distribution called Alpine. We will discuss the use of Alpine in more detail in the next chapter.

Inside the image, we will create a directory app, where the project file will be located.

The container will be launched using the command "python3", "console_calculator.py".

  1. To build the image, the docker build command is used. Each image must also be assigned a tag. A tag is a unique identifier that can be assigned to an image. The tag is specified using the -t flag:

docker build -t python-console-calculator:01 .

The period at the end of the command indicates that the Dockerfile is located in the current directory.

You can display the list of created images using:

docker images

Image24

To launch the container, use: 

docker run --rm -it python-console-calculator:01

Image1

Let's test the functionality of the program by performing a few simple arithmetic operations:

Image3

To exit the program, you need to press the q key.

Since we specified the --rm flag when starting the container, the container will be automatically removed.

You can also run the container in daemon mode, i.e., in the background. To do this, include the -d flag when starting the container:

docker run -dit python-console-calculator:01

After that, the container will appear in the list of running containers:

Image10

When starting the container in the background to access our script, you need to use docker exec, which executes a command inside the container. First, you need to start a shell (bash or sh), then manually run the script inside the container.

To do this, use the docker exec command, passing the sh command as an argument to open the shell inside the container (where 4f1b8b26c607 is the unique container ID displayed in the CONTAINER ID column of the docker ps output):

docker exec -it 4f1b8b26c607 sh

Then, run the script manually:

python console_calculator.py

Image16

To remove a running container, you need to use the docker rm command and pass the container's ID or name. You also need to use the -f flag, which will force the removal of a running container:

docker rm -f 186e8f43ca60

Optimizing Docker Images

When creating Docker images, there is one main rule: finished images should be compact and occupy as little space as possible. Additionally, the smaller the image, the faster it is built. This can play a key role when using CI/CD methods or when releasing software in the Time to Market model.

Proper Selection of the Base Image

As the first recommendation, it's important to choose the base image wisely. For example, instead of using various Linux distribution images like Ubuntu, Oracle Linux, Rocky Linux, and many others, you can directly choose an image that already comes with the required programming language, framework, or other necessary technology. Examples of such images include:

  • node for working with the Node.js platform
  • A pre-built image with Nginx
  • ibmjava for working with the Java programming language
  • postgres for working with the PostgreSQL databases
  • redis for working with the NoSQL Redis

Using a specific image instead of an operating system image has the following advantages:

  • There is no need to install the main tool (programming language, framework, etc.), so the image won't be "cluttered" with unnecessary packages, preventing an increase in size.

  • Images that come with pre-installed software (like Nginx, Redis, PostgreSQL, Grafana, etc.) are always created by the developers of the software themselves. This means that users do not need to configure the program to run it (except in cases where it needs to be integrated with their service).

Let's consider this recommendation with a practical example. We will use a simple Python program that prints "Hello from Python!".  First, we will build an image using debian as the base image.

  1. Create and navigate to the directory where the project files will be stored:

mkdir dockerfile-python && cd dockerfile-python
  1. Create the test.py file with the following content:

print("Hello from Python!")
  1. Next, create a Dockerfile with the following content:

FROM debian:latest

COPY test.py .

RUN apt update 
RUN apt -y install python3

CMD ["python3", "test.py"]

To run Python programs, you also need to install the Python interpreter.

  1. Then, build the image:

docker build -t python-debian:01 .

Image20

Let’s check the Docker image size: 

docker images

Image8

The image takes up 185MB, which is quite a lot for an application that just prints a single line to the terminal.

Now, let's choose the correct base image, which is based on the Alpine distribution.

Another feature of base images is that for many images, there are special versions in the form of slim and alpine images, which are even smaller. Let's look at the example of the official Python 3.10 image. The python:3.10 image takes up a whole 1 GB, whereas the slim version is much smaller—127 MB. And the alpine image is only 50 MB.

Image17

Slim images are images that contain the minimum set of packages necessary to run a finished application. These images lack most packages and libraries. Slim images are created from both regular Linux distributions (such as Ubuntu or Debian) and Alpine-based distributions.

Alpine images are images that use the Alpine distribution as the operating system— a lightweight Linux distribution that takes up about 5 MB of disk space (without the kernel). It differs from other Linux distributions in that it uses a package manager called apk, lacks the system initialization system, and has fewer pre-installed programs.

When using both slim and Alpine images, it is essential to thoroughly test your application, as the required packages or libraries might be missing in such distributions.

Now, let's test our application using the Python image with Alpine.

  1. Return to the previously used Dockerfile and replace the base image from debian to the python:alpine3.19 image. You should also remove the two RUN instructions, as there will be no need to install the Python interpreter:

FROM python:alpine3.19

COPY test.py .

CMD ["python3", "test.py"]
  1. Use a new tag to build the image:

Image21

  1. List all the Docker images. Check the image size and compare with the previous one: 

Image11

Since we chose the correct base image with Python already preinstalled, the image size was reduced from 185 MB to 43.8 MB.

Reducing the Number of Layers

Docker images are based on the concept of layers. A layer represents a change made to the image's file system. These changes include copying/creating directories and files or installing packages. It is recommended to use as few layers as possible in the image. Among all Dockerfile instructions, only the FROM, COPY, ADD, and RUN instructions create layers that increase the final image size. All other instructions create temporary intermediate images and do not directly increase the image size.

Let's take the previously used Dockerfile and modify it according to new requirements. Suppose we need to install additional packages using the apt package manager:

FROM debian:latest

COPY test.py .

RUN apt update 
RUN apt -y install python3 htop net-tools mc gcc

CMD ["python3", "test.py"]

Build the image:

docker build -t python-non-optimize:01 .

Check the size of the created Docker image:

docker images

Image14

The image size was 570 MB. However, we can reduce the size by using fewer layers. Previously, our Dockerfile contained two RUN instructions, which created two layers. We can reduce the image size by combining the apt update and apt install commands using the && symbol, which in Bash means that the next command will only run if the first one completes successfully.

Another important point is to remove cache files left in the image after package installation using the apt package manager (this also applies to other package managers such as yum/dnf and apk). The cache must be removed. For distributions using apt, the cache of installed programs is stored in the /var/lib/apt/lists directory. Therefore, we will add a command to delete all files in that directory within the RUN instruction without creating a new layer:

FROM debian:latest

COPY test.py .

RUN apt update && apt -y install python3 htop net-tools mc gcc && rm -rf /var/lib/apt/lists/*

CMD ["python3", "test.py"]

Build the image:

docker build -t python-optimize:03 .

And check the size:

Image7

The image size was reduced from the initial 570 MB to the current 551 MB.

Using Multi-Stage Builds

Another significant way to reduce the size of the created image is by using multi-stage builds. These builds, which involve two or more base images, allow us to separate the build environment from the runtime environment, effectively removing unnecessary files and dependencies from the final image. These unnecessary files might include libraries or development dependencies that are only needed during the build process.

Let’s explore this approach with a practical example using the Node.js platform. Node.js should be installed beforehand, following our guide.

We will first build the application image without multi-stage builds to evaluate the difference in size.

  1. Create a directory for the project:

mkdir node-app && cd node-app
  1. Initialize a new Node.js application:

npm init -y

Image12

  1. Install the express library:
npm install express
  1. Create an index.js file with the content:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

app.listen(PORT, () => {
  console.log(Server is running on port${PORT});
});
  1. Create Dockerfile with this content:
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY index.js .
EXPOSE 3000
CMD ["npm", "start"]
  1. Build the image:
docker build -t node-app:01 .

Image15

  1. Check the size:
docker images

Image19

  1. The image size was 124 MB. Now let's rewrite the Dockerfile to use two images, transforming it into the following form:
FROM node:14 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY index.js .

FROM gcr.io/distroless/base-debian10 AS production
WORKDIR /app
COPY --from=builder /app .
EXPOSE 3000
CMD ["npm", "start"]
  1. Build the image:
docker build -t node-app:02 .

Image18

  1. List the Docker images and check the size:
docker images

Image23

As a result, the image size was drastically reduced—from 124 MB to 21.5 MB.

Conclusion

In this article, we created our own Docker image and explored various ways to run it. We also paid significant attention to optimizing Docker images. Through optimization, we can greatly reduce the image size, which allows for faster image builds.

Docker
22.01.2025
Reading time: 12 min

Similar

Docker

How to Install Docker on MacOS

Docker is a platform that makes it easier to create, deploy, and operate applications in containers. Containers enable developers to bundle an application's dependencies, including as libraries, frameworks, and runtime environments, and ship it as a single package. This ensures that the program runs reliably and consistently, independent of the environment in which it is deployed. If you have troubles with that, here's our instruction how to deploy server with Docker. Docker allows you to automate the deployment of software inside lightweight, portable containers. These containers may operate on any system with Docker installed, making it simple to deploy apps across several settings, such as a developer's laptop, a testing server, or a production environment on the cloud. Docker also includes tools for managing and orchestrating containers at scale, making it simpler to deploy, scale, and manage complex applications in production environments. Below are the requirements to prepare for the installation of docker on MacOS:  A supported version of MacOS. Docker Desktop is compatible with the latest macOS versions. This includes the current macOS release as well as the two previous releases. As new major versions of macOS become widely available, Docker stops supporting the oldest version and instead supports the most recent version (along with the prior two). RAM: minimum of 4 GB. This is to optimize Docker performance especially when operating multiple containers.  In installing docker, you can either install it interactively or manually or via the command line interface. Here’s the guide on how to do the installation with both methods. Manual Installation Download the installer from the official docker website using the following links: Apple Silicon processor Intel chip processor Install Docker Desktop by double-clicking the Docker.dmg:  And drag and drop it to the Application folder. By default, the Docker Desktop is installed at /Applications/Docker. Wait for the copying to finish. Double-click the Docker from the Applications folder to proceed with the installation. Click Accept to continue in the Docker Subscription Service Agreement page. From the installation window, choose either: Use recommended settings (Requires password) Use advanced settings Click Finish.  Verify if installation is successful. A Docker icon should appear on the menu bar when the Docker Desktop is installed and running. A notification will appear stating that Docker is running. Install using Command Line Interface Once Docker.dmg is downloaded from the official docker website, login as a super user / root in a terminal to install Docker Desktop in the Application folder. Execute the below commands respectively.  hdiutil attach Docker.dmg /Volumes/Docker/Docker.app/Contents/MacOS/install hdiutil detach /Volumes/Docker If running as a normal user, execute the command with sudo: sudo hdiutil attach Docker.dmg sudo /Volumes/Docker/Docker.app/Contents/MacOS/install sudo hdiutil detach /Volumes/Docker Installation might take some time to complete since the system may do various security checks while installing Docker on Mac. Troubleshooting Some of the common issues that the user might encounter during the installation of MacOS are:  Users may not check the MacOs version of their machine. Take note of the system requirements when installing Docker on MacOS to avoid installation failure and unexpected behavior (like docker image becomes corrupted). Errors during the installation process may occur such as failed downloads, incomplete installation, etc. Go back and check the system and hardware compatibility of the machine.  Conflict with existing software. This requires troubleshooting and investigating system logs. Usually, this can be solved by removing the problematic software.  Permission and security issues. When installing Docker on MacOS, ensure that the machine has all the required permission to access system resources, like directory, network, etc.  Conclusion To summarize, installing Docker on MacOS provides various opportunities for both developers and system administrators. Docker technology provides resources with an enhanced development workflow, an efficient procedure for delivering apps, and consistent system environments. Embrace containerization to broaden your development horizons. Check what Hostman VPS Servers can give you.
30 April 2025 · 4 min to read
Docker

Installing and Using Nexus Repository for Artifact Storage

In software development, "artifact" is a component of a developed software product. Artifacts include executable and binary files, software packages, and more. As the product's architecture and functionality increase, the number of artifacts grows exponentially, and you need a reliable storage solution that can manage large volumes of artifacts efficiently.  One such solution is Nexus Repository by Sonatype.  Nexus supports over 15 artifact formats, including APT, Docker, Go, Helm, Maven, npm, PyPi, and more.  There are two versions of Nexus Repository: Free version – Includes essential repository management features. Commercial version – Offers customer support and a broader range of supported artifact types. In this guide, we will install the free version of Nexus Repository. Prerequisites You can install Nexus Repository on a Linux, Windows, or MacOS machine. In this guide, we will use a Hostman cloud server running Ubuntu. The server must meet the following minimum requirements: 4-core CPU. 8-core or higher is recommended. 8 GB RAM  50 GB of free disk space (excluding OS and other installed software). If there is insufficient space, Nexus will not start. The official Sonatype website provides recommended system requirements based on the number of repositories and stored artifacts. Installing Nexus Repository Step 1: Install Java First, update the package list: sudo apt update Then, install Java 8 using OpenJDK: sudo apt -y install openjdk-8-jre-headless After installation, verify Java's version: java -version If you have multiple Java versions installed, switch to Java 8: sudo update-alternatives --config java Select the correct version using the TAB key and confirm with Enter. Step 2: Download and Extract Nexus We will install Nexus in the /opt directory. Download the latest Nexus archive: sudo wget https://download.sonatype.com/nexus/3/latest-unix.tar.gz Extract the archive to /opt: sudo tar -zxvf latest-unix.tar.gz -C /opt Rename the extracted directory (for easier management): sudo mv /opt/nexus-3.61.0-02 /opt/nexus Make sure to specify the correct version number in your case.  Step 3: Create a Dedicated User for Nexus Create a new user named nexus: sudo adduser nexus Disable direct login for this user: sudo usermod nexus -s Set the correct ownership for Nexus directories: sudo chown -R nexus:nexus /opt/nexus /opt/sonatype-work Step 4: Configure Nexus Edit the Nexus configuration file: sudo nano /opt/nexus/bin/nexus.rc Uncomment (remove #) and set the user as nexus: run_as_user="nexus" Save and exit the file. Step 5: Create a Systemd Service for Nexus Create a new service file: sudo nano /etc/systemd/system/nexus.service Add the following content: [Unit] Description=Nexus Repository Manager After=network.target [Service] Type=forking LimitNOFILE=65536 ExecStart=/opt/nexus/bin/nexus start ExecStop=/opt/nexus/bin/nexus stop User=nexus Restart=on-abort [Install] WantedBy=multi-user.target Save and exit the file. Step 6: Start and Enable Nexus Start Nexus: sudo systemctl start nexus Check Nexus status: systemctl status nexus If the status is active, Nexus is running successfully. Enable Nexus to start on boot: sudo systemctl enable nexus Step 7: Verify Nexus Startup Nexus takes 2-3 minutes to fully start. To check the logs: tail -f /opt/sonatype-work/nexus3/log/nexus.log Once you see: Started Sonatype Nexus OSS Nexus is ready. By default, the Nexus web interface is accessible on port 8081: http://your-server-ip:8081 Initial Setup of Nexus Repository Step 1: Log into Nexus Open the Nexus web interface. Click the Sign in button (top-right corner). Retrieve the default admin password by running: cat /opt/sonatype-work/nexus3/admin.password Use this password to log in as admin. Step 2: Initial Configuration Set a new password for the admin user. Enable or disable anonymous access: Enabled: Any user with the repository URL can browse/download artifacts without authentication. Disabled: Authentication (login/password) is required. Nexus is now ready to use. Creating a Docker Repository in Nexus Step 1: Create a Docker Repository Log in as admin. Go to Server Administration and Configuration (gear icon). In the left menu, select Repositories. Click Create repository. Choose docker (hosted). Step 2: Configure the Repository Nexus supports three types of repositories: Hosted: Stores artifacts directly in Nexus. Proxy: Fetches artifacts from remote repositories (e.g., APT). Group: Combines multiple repositories into one unified endpoint. For a Docker repository: Set a repository name, e.g., docker-images. Enable HTTP access (check the box). Assign a port number (e.g., 8083). Save the settings. Step 3: Configure Docker to Work with Nexus By default, Docker does not allow HTTP connections. To enable HTTP access: Edit or create the Docker daemon configuration file: sudo nano /etc/docker/daemon.json Add the following configuration: { "insecure-registries": ["166.1.227.189:8083"] } (Replace 166.1.227.189:8083 with your Nexus server IP and port.) Save and exit the file. Restart the Docker service: sudo systemctl restart docker Warning: Restarting Docker affects running containers. Containers without the --restart=always flag may not restart automatically. Step 4: Push a Docker Image to Nexus Log in to Nexus via Docker: docker login 166.1.227.189:8083 You can use the admin username and the password you set earlier. Tag an image (e.g., alpine): docker tag alpine:latest 166.1.227.189:8083/alpine-test Verify the new tag: docker images Push the image to Nexus: docker push 166.1.227.189:8083/alpine-test Confirm the upload: Open the Nexus web interface. Go to the docker-images repository. The alpine-test image should be listed. Your Nexus repository is now set up for Docker image storage! HTTPS Configuration The correct approach when working with Docker repositories is to use the HTTPS protocol. To configure HTTPS in Nexus, follow these steps: Navigate to the /opt/nexus/etc/ssl directory: cd /opt/nexus/etc/ssl Use keytool to generate a self-signed certificate: sudo keytool -genkeypair -keystore keystore.jks -storepass test12345 -keypass test12345 -alias jetty -keyalg RSA -keysize 2048 -validity 1000 -dname "CN=*.${NEXUS_DOMAIN}, OU=test, O=test1, L=Unspecified, ST=Unspecified, C=RU" -ext "SAN=DNS:nexus-repo.com,IP:166.1.227.189" -ext "BC=ca:true" Replace the following values with your own: -keystore keystore.jks — Name of the file where the key will be stored, using the .jks format. -storepass test12345 — Password for accessing the key store. -keypass test12345 — Password for accessing the private key. -ext "SAN=DNS:nexus-repo.com,IP:166.1.227.189" — Specifies your Nexus server's domain name and IP address. If a local domain is used, it must be added to the /etc/hosts file (for Linux) or C:\Windows\System32\drivers\etc\hosts in Windows. Next, extract the server certificate from the generated keystore.jks file using the following command: sudo keytool -export -alias jetty -keystore keystore.jks -rfc -file nexus.cert The output will be a certificate file named nexus.cert. Now, edit the Nexus configuration file nexus-default.properties located in /opt/nexus/etc: sudo nano /opt/nexus/etc/nexus-default.properties Find the section with the comment # Jetty section, and add the following parameter: application-port-ssl=8443 This specifies the port where HTTPS will be available. In the same section, add this line: nexus-args=${jetty.etc}/jetty.xml,${jetty.etc}/jetty-http.xml,${jetty.etc}/jetty-https.xml,${jetty.etc}/jetty-requestlog.xml Next, edit the jetty-https.xml file located in /opt/nexus/etc/jetty: sudo nano /opt/nexus/etc/jetty/jetty-https.xml Locate the block named sslContextFactory. In the fields KeyStorePassword, KeyManagerPassword, TrustStorePassword, enter the password used during certificate generation. In this example, the password is test12345. In the parameters KeyStorePath and TrustStorePath, specify the name of the generated certificate. After making these changes, restart the Nexus service: sudo systemctl restart nexus Installing the Certificate on Linux In Linux, we must install the certificate at the OS level. Otherwise, when trying to authenticate to the repository using the docker login command, the following error may occur: x509: certificate signed by unknown authority To install the certificate on Ubuntu/Debian, follow these steps: Install the ca-certificates package: sudo apt -y install ca-certificates The certificate must be in .crt format, as other formats are not supported. Since the certificate was generated as .cert, rename it to .crt: sudo mv nexus.cert nexus.crt Copy the certificate to /usr/local/share/ca-certificates: sudo cp nexus.crt /usr/local/share/ca-certificates Install the certificate using the following command: sudo update-ca-certificates Configuring HTTPS in the Nexus Repository To configure HTTPS in the repository: Open the Nexus web interface and log in as an administrator. Navigate to the Server Administration and Configuration section (gear icon). In the left menu, select Repositories, find the required repository, check the box next to HTTPS, and specify a port that is not already in use on the server, such as 8344. 4 Save the changes. On the server, run the docker login command, specifying the repository address and HTTPS port: docker login nexus-repo.com:8344 You can log in using the admin account. Pushing an Image to the Repository To test pushing an image, let's use nginx: Assign a tag to the image. The format for Docker image tags is as follows: image:tag registry_address:repository_port/image_name Example: docker tag nginx:latest nexus-repo.com:8344/nginx-test Verify that the new image exists: docker images Push the image to the repository: docker push nexus-repo.com:8344/nginx-test Open the Nexus web interface, navigate to the repository, and confirm that the image was successfully uploaded. Conclusion Nexus Repository is an excellent solution for storing and managing artifacts. Supporting a wide range of artifact formats, it is suitable for both small development teams and larger enterprises.
11 March 2025 · 8 min to read
Docker

How To Install and Use Docker Compose on Ubuntu

Docker Compose has fundamentally changed how developers approach containerized applications, particularly when coordinating services that depend on one another. This tool replaces manual container management with a structured YAML-driven workflow, enabling teams to define entire application architectures in a single configuration file.  For Ubuntu environments, this translates to reproducible deployments, simplified scaling, and reduced operational overhead. This guide provides a fresh perspective on Docker Compose installation and usage, offering deeper insights into its practical implementation. Prerequisites Before you begin this tutorial, you'll need a few things in place: Deploy an Ubuntu cloud server instance on Hostman. Ensure you have a user account with sudo privileges or root access. This allows you to install packages and manage Docker. Install Docker and have it running on your server, as Docker Compose works on top of Docker Engine. Why Docker Compose Matters Modern applications often involve interconnected components like APIs, databases, and caching layers. Managing these elements individually with Docker commands becomes cumbersome as complexity grows. Docker Compose addresses this by allowing developers to declare all services, networks, and storage requirements in a docker-compose.yml file. This approach ensures consistency across environments—whether you’re working on a local Ubuntu machine or a cloud server. For example, consider a web application comprising a Node.js backend, PostgreSQL database, and Redis cache. Without Docker Compose, each component requires separate docker run commands with precise networking flags. With Compose, these relationships are organized once, enabling one-command setups and teardowns. Docker Compose Installation Follow these steps to install Docker Compose on your Ubuntu machine: Step 1: Verify that the Docker Engine is Installed and Running Docker Compose functions as an extension of Docker, so verify its status with: sudo systemctl status docker Example output: ● docker.service - Docker Application Container Engine Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2025-02-20 08:55:04 GMT; 5min ago TriggeredBy: ● docker.socket Docs: https://docs.docker.com Main PID: 2246435 (dockerd) Tasks: 9 Memory: 53.7M CPU: 304ms CGroup: /system.slice/docker.service └─2246435 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock If inactive, start it using sudo systemctl start docker. Step 2: Update System Packages Refresh your package lists to ensure access to the latest software versions: sudo apt-get update You will see: Hit:1 https://download.docker.com/linux/ubuntu jammy InRelease Hit:2 http://archive.ubuntu.com/ubuntu jammy InRelease Hit:4 http://security.ubuntu.com/ubuntu jammy-security InRelease Hit:5 http://repo.hostman.com/ubuntu focal InRelease Hit:6 http://archive.ubuntu.com/ubuntu jammy-updates InRelease Hit:7 http://archive.ubuntu.com/ubuntu jammy-backports InRelease Hit:3 https://prod-cdn.packages.k8s.io/repositories/isv:/kubernetes:/core:/stable:/v1.31/deb InRelease Hit:8 https://packages.redis.io/deb jammy InRelease Reading package lists... Done Step 3: Install Foundational Utilities Secure communication with Docker’s repositories requires these packages: sudo apt-get install ca-certificates curl  Step 4: Configure Docker’s GPG Key Authenticate Docker packages by adding their cryptographic key: sudo install -m 0755 -d /etc/apt/keyringssudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.ascsudo chmod a+r /etc/apt/keyrings/docker.asc This step ensures packages haven’t been altered during transit. Step 5: Integrate Docker’s Repository Add the repository tailored to your Ubuntu version: echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null The command auto-detects your OS version using VERSION_CODENAME. Step 6: Install the Docker Compose Plugin Update repositories and install the Compose extension: sudo apt updatesudo apt-get install docker-compose-plugin Step 7: Validate the Installation Confirm successful setup with: docker compose version The output displays the Docker Compose version: Docker Compose version v2.33.0 Building a Practical Docker Compose Project Let’s deploy a web server using Nginx to demonstrate Docker Compose’s capabilities. Step 1. Initialize the Project Directory Create a dedicated workspace: mkdir ~/compose-demo && cd ~/compose-demo Step 2. Define Services in docker-compose.yml Create the configuration file: nano docker-compose.yml Insert the following content: services: web: image: nginx:alpine ports: - "8080:80" volumes: - ./app:/usr/share/nginx/html In the above YAML file: services: Root element declaring containers. web: Custom service name. image: Uses the Alpine-based Nginx image for reduced footprint. ports: Maps host port 8080 to container port 80. volumes: Syncs the local app directory with the container’s web root. Step 3. Create Web Content Build the HTML structure: mkdir app nano app/index.html Add this HTML snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Docker Compose Test</title> </head> <body> <h1>Hello from Docker Compose!</h1> </body> </html> Orchestrating Containers: From Launch to Shutdown Let’s explore how you can use Docker Compose for container orchestration: Start Services in Detached Mode Launch containers in the background: docker compose up -d Example output: [+] Running 2/2 ✔ Network compose-demo_default Created ✔ Container compose-demo-web-1 Started Docker Compose automatically pulls the Nginx image if missing and configures networking. Verify Container Status Check operational containers: docker compose ps -a Access the Web Application Visit http://localhost:8080 locally or http://<SERVER_IP>:8080 on remote servers. The test page should display your HTML content. Diagnose Issues via Logs If the page doesn’t load or if you encounter any issues, you can inspect container logs: docker compose logs web Example output: web-1 | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration web-1 | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ web-1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh web-1 | 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf web-1 | 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf web-1 | /docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh … Graceful Shutdown and Cleanup Stop containers temporarily: docker compose stop Example output: [+] Stopping 1/1 ✔ Container compose-demo-web-1  Stopped Remove all project resources: docker compose down Example output: [+] Running 2/2 ✔ Container compose-demo-web-1  Removed ✔ Network compose-demo_default  Removed Command Reference: Beyond Basic Operations While the workflow above covers fundamentals, these commands enhance container management: docker compose up --build: Rebuild images before starting containers. docker compose pause: Freeze containers without terminating them. docker compose top: Display running processes in containers. docker compose config: Validate and view the compiled configuration. docker compose exec: Execute commands in running containers (e.g., docker compose exec web nginx -t tests Nginx’s configuration). Conclusion Docker Compose transforms multi-container orchestration from a manual chore into a streamlined, repeatable process. By adhering to the steps outlined—installing Docker Compose, defining services in YAML, and leveraging essential commands—you can manage complex applications with confidence.
26 February 2025 · 7 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support