A Deep Dive into Docker
local graph
Chapter 9 — A Deep Dive into Docker
Section titled “Chapter 9 — A Deep Dive into Docker”The advent of Docker has revolutionized the way we run, deploy, and maintain our applications. With the rise of containerization, we’ve been able to abstract away much of the underlying infrastructure and dependencies that applications rely on, making it easier than ever to deploy and manage them across different environments. However, with great power comes great responsibility, and we must understand the internals of Docker and establish good practices to ensure that our applications are secure, reliable, and performant.
In this chapter, we’ll delve into the nitty-gritty of Docker, exploring its architecture, components, and key features. We’ll also examine some of the helper projects that have emerged on top of Docker, such as Docker Compose and Kubernetes, and learn how to use them to build more complex and scalable applications. Throughout, we’ll emphasize best practices for working with Docker, such as creating efficient Docker images, managing containers, and optimizing performance. By the end of this chapter, you’ll be well-equipped to confidently run your applications inside Docker and leverage its full power to build robust and scalable systems.
This chapter covers the following topics:
- Docker advanced use cases
- Docker Compose
- Advanced Dockerfile techniques
- Docker orchestration
Docker advanced use cases
Section titled “Docker advanced use cases”While using Docker and its CLI, there are a lot of things we will need to take care of in terms of the life cycle of the container, build process, volumes, and networking. Some of those things you can automate by using other tools, but it’s still useful to know what’s going on underneath.
Running public images
Section titled “Running public images”A lot of public images you can find on Docker Hub (https://hub.docker.com) have initialization scripts available that take configuration from environment variables or the mounted files to a predefined directory.
The most commonly used image that uses both techniques is images with databases. Let’s look for an official Docker PostgreSQL image. You can find the one we’ll be using here: https://hub.docker.com/_/postgres.
To run the official PostgreSQL Docker image, you can use the following command:
admin@myhome:~$ docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgresIn this command, we have the following:
--name some-postgresgives the container a name of some-postgres-e POSTGRES_PASSWORD=mysecretpasswordsets the password for the default PostgreSQL user (postgres)-druns the container in the background;postgresspecifies the image to use
It’s also possible to override the default user (postgres) by adding a POSTGRES_USER environment variable. Other configuration environment variables are listed in the documentation.
A very useful feature you can use when working with the official PostgreSQL image is database pre-population using SQL scripts. To achieve this, you will need to bind mount a local directory with scripts to /docker-entrypoint-initdb.d inside the container. There are two things you will need to take care of: empty data directory and making sure all scripts are finished with success. An empty data directory is necessary as this will act as the entry point where you can load your SQL or shell scripts; it also prevents data loss. If any of the scripts finish with an error, the database won’t be started.
Similar features are provided for other Docker images running any other database available in Docker Hub.
Another useful official image you could use is nginx: it’s probably much simpler to use as you already have a configured web server inside and you will need to provide either content for it to serve (HTML files, JavaScript, or CSS) or override the default configuration.
Here is an example of mounting a static HTML website to a container:
admin@myhome:~$ docker run -p 8080:80 -v /your/webpage:/usr/share/nginx/html:ro -d nginxIn this command, we have the following:
-p 8080:80: This option maps port8080on the host machine to port80inside the container. This means that when someone accesses port8080on the host machine, it will be redirected to port80in the container.-v /your/webpage:/usr/share/nginx/html:ro: This option mounts the/your/webpagedirectory on the host machine to the/usr/share/nginx/htmldirectory inside the container. Therooption means that the mount is read-only, which means that the container cannot modify the files in the/your/webpagedirectory.-d: This option tells Docker to run the container in detached mode, which means that it will run in the background.nginx: This is the name of the Docker image that will be used to run the container. In this case, it’s the official nginx image from Docker Hub.
We can override the default nginx configuration like so:
admin@myhome:~$ docker run -p 8080:80 -v ./config/nginx.conf:/etc/nginx/nginx.conf:ro -d nginxIn this command, most of the previous options repeat themselves except one: -v ./config/nginx.conf:/etc/nginx/nginx.conf:ro. This option mounts the ./config/nginx.conf file on the host machine to the /etc/nginx/nginx.conf file inside the container. The ro option means that the mount is read-only, which means that the container cannot modify the nginx.conf file.
Running a debugging container
Section titled “Running a debugging container”Containers running in production usually have very few tools that are useful for troubleshooting installed. On top of that, those containers aren’t running as root users and have multiple security mechanisms to prevent tampering. With that in mind, how do we get into the Docker network to debug if something is not working?
The answer to that question is just running another container we could get into. It would have some tools pre-installed or would allow us to install whatever we need while running. There are multiple techniques we can use to achieve this.
First, we will need a process that will run indefinitely until we stop it manually. While this process is running, we could step in and use the docker exec command to get inside the running Docker.
Knowing Bash scripting, the easiest way to run this process is to create a while loop:
admin@myhome:~$ docker run -d ubuntu while true; do sleep 1; doneAnother method is to use the sleep program:
admin@myhome:~$ docker run -d ubuntu sleep infinityAlternatively, you could just try to read a special device, /dev/null, that is outputting nothing and the tail command:
admin@myhome:~$ docker run -d ubuntu tail -f /dev/nullFinally, when one of these commands is running inside the network you’re trying to troubleshoot, you can run a command inside it, and effectively be able to run commands from within the environment you need to investigate:
admin@myhome:~$ docker exec -it container_name /bin/bashLet us now look at cleaning up unused containers.
Cleaning up unused containers
Section titled “Cleaning up unused containers”Docker images can accumulate over time, especially when you frequently build and experiment with containers. Some of these images may no longer be needed, and they can take up valuable disk space. To clean up these unused images, you can use the docker image prune command. This command removes all images that are not associated with a container, also known as dangling images.
In addition to unused images, there may also be leftover containers that were not removed properly. These containers can be identified using the docker ps -a command. To remove a specific container, you can use the docker rm <container_id> command, where <container_id> is the identifier of the container you want to remove. If you want to remove all stopped containers, you can use the docker container prune command.
It’s good practice to regularly perform image and container cleanup to maintain a healthy Docker environment. This not only saves disk space but also helps prevent potential security vulnerabilities associated with unused resources. It is also best practice to remove all sensitive information, such as passwords and keys, from the containers and images.
Here’s an example of using the docker image prune command to remove dangling images:
admin@myhome:~$ docker image pruneDeleted Images:deleted:sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6efdeleted:sha256:c937c4dd0c2eaf57972d4f80f55058b3685f87420a9a9fb9ef0dfe3c7c3e60bcTotal reclaimed space: 65.03MBHere’s an example of using the docker container prune command to remove all stopped containers:
admin@myhome:~$ docker container pruneWARNING! This will remove all stopped containers.Are you sure you want to continue? [y/N] yDeleted Containers:8c922b2d9708fcee6959af04c8f29d2d6850b3a3b3f3b966b0c360f6f30ed6c86d90b6cbc47dd99b2f78a086e959a1d18b7e0cf4778b823d6b0c6b0f6b64b6c64Total reclaimed space: 0BTo automate these tasks, you can use crontab to schedule regular cleanups. To edit your crontab file, you can use the crontab -e command. Here’s an example of scheduling a daily cleanup of dangling images at 3 A.M.:
0 3 * * * docker image prune -fThis line is made up of five fields separated by spaces. These fields represent the minutes, hours, days of the month, months, and days of the week when the command will be executed. In this example, the command will be executed at 3 A.M. every day. Let’s look at each element in detail:
- The first field,
0, represents the minutes. In this case, we want the command to be executed at exactly 0 minutes past the hour. - The second field,
3, represents the hours. In this case, we want the command to be executed at 3 A.M. - The third field,
*, represents the days of the month. The asterisk means “any” day of the month. - The fourth field,
*, represents the months. The asterisk means “any” month of the year. - The fifth field,
*, represents the days of the week. The asterisk means “any” day of the week.1represents Monday,2represents Tuesday, and so on until7, which represents Sunday.
Here’s an example of scheduling a weekly cleanup of stopped containers at 4 A.M. on Sundays:
0 4 * * 7 docker container prune -fThe -f flag is used to force the removal of the images or containers without confirming this with the user.
To list all existing cron jobs for your user, you can use the crontab -l command. More about crontab can be found online or by using the man crontab command. A great how-to article about using it can be found in the Ubuntu Linux knowledge base: https://help.ubuntu.com/community/CronHowto.
Docker volumes and bind mounts
Section titled “Docker volumes and bind mounts”As mentioned in the previous chapter, Docker volumes and bind mounts are two different ways to persist data generated by a Docker container. Volumes are managed by Docker and exist outside the container’s filesystem. They can be shared and reused between containers, and they persist even if the original container is deleted. On the other hand, bind mounts link a file or directory on the host system to a file or directory in the container. The data in bind mounts is directly accessible from the host and the container and persists for as long as the host file or directory remains.
To use a Docker volume, you can use the -v or --mount flag when you run the docker run command and specify the host source and container destination. For example, to create a volume and mount it to the container at /app/data, you can run the following command:
admin@myhome:~$ docker run -v my_data:/app/data <image_name>To use a bind mount, you can use the same flags and specify the host source and container destination, just like with a volume. However, instead of using a volume name, you need to use the host file or directory path. For example, to bind mount the /host/data host directory to the container at /app/data, you can run the following command:
admin@myhome:~$ docker run -v /host/data:/app/data <image_name>When using bind mounts in Docker, you may encounter permission problems with the files and directories within the bind mount. This is because the user IDs (UIDs) and group IDs (GIDs) of the host and container may not match, leading to issues with accessing or modifying the data in the bind mount.
For example, if the host file or directory is owned by a user with UID 1000, and the corresponding UID in the container is different, the container may not be able to access or modify the data in the bind mount. Similarly, if the group IDs do not match, the container may not be able to access or modify the data due to group permissions.
To prevent these permission problems, you can specify the UID and GID of the host file or directory when you run the docker run command. For example, to run a container with a bind mount as the UID and GID 1000, you can run the following command:
admin@myhome:~$ docker run -v /local/data:/app/data:ro,Z --user 1000:1000 <image_name>In this example, the :ro flag specifies that the bind mount should be read-only, and the ,Z flag tells Docker to label the bind mount with a private label so that it cannot interact with other containers. The --user flag sets the UID and GID of the process running inside the container to 1000.
By specifying the UID and GID of the host file or directory in the container, you can prevent permission problems with bind mounts in Docker and ensure that the container can access and modify the data as expected.
Docker networking advanced use cases
Section titled “Docker networking advanced use cases”Docker provides a convenient way to manage the networking of containers in a user-defined network. By using Docker networks, you can easily control the communication between containers and isolate them from the host network.
Docker bridge networking is a default network configuration that enables communication between containers running on the same host. It works by creating a virtual network interface on the host system that acts as a bridge between the containers and the host network. Each container on the bridge network is assigned a unique IP address that allows it to communicate with other containers and the host.
Bridge networks are isolated from each other, meaning that containers connected to different bridge networks cannot communicate with each other directly. To achieve communication between containers on different networks, you can use the Docker service discovery mechanism, such as connecting to a specific container IP address or using a load balancer.
To use bridge networking in practice, you can create a new bridge network using the Docker CLI. For example, you can use the docker network create --driver bridge production-network command to create a new bridge network named production-network. After the network is created, you can then connect your containers to the network by using the --network option in the docker run command. You can use the docker run --network production-network my-image command to run a container from the my-image image on the production-network network.
In addition to creating a new bridge network, you can connect containers to the default bridge network that is automatically created when you install Docker. To connect a container to the default network, you do not need to specify the --network option in the docker run command. The container will automatically be connected to the default bridge network and assigned an IP address from the bridge network subnet.
Now, if you create multiple networks, by default, they will be separated and no communication will be allowed between them. To allow communication between two bridge networks, such as production-network and shared-network, you will need to create a network connection between the two networks by connecting a container of your choosing to those two networks or allowing all communication between the two networks. The latter option, if possible, is not supported.
The final option is to use Docker Swarm mode and overlay network mode, which we will get into a bit later in this chapter in the Docker orchestration section.
The following is an example of how to connect a container to two networks at the same time. First, let’s create a production and shared network:
admin@myhome:~$ docker network create production-networkfd1144b9a9fb8cc2d9f65c913cef343ebd20a6b30c4b3ba94fdb1fb50aa1333cadmin@myhome:~$ docker network create shared-networka544f0d39196b95d772e591b9071be38bafbfe49c0fdf54282c55e0a6ebe05adNow, we can start a container connected to production-network:
admin@myhome:~$ docker run -itd --name prod-container --network production-network alpine shUnable to find image 'alpine:latest' locallylatest: Pulling from library/alpine8921db27df28: Pull completeDigest:sha256:f271e74b17ced29b915d351685fd4644785c6d1559dd1f2d4189a5e851ef753aStatus: Downloaded newer image for alpine:latest287be9c1c76bd8aa058aded284124f666d7ee76c73204f9c73136aa0329d6bb8Let’s do the same for shared-network:
admin@myhome:~$ docker run -itd --name shared-container --network shared-network alpine sh38974225686ebe9c0049147801e5bc777e552541a9f7b2eb2e681d5da9b8060bLet’s investigate if both containers are running:
admin@myhome:~$ docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES38974225686e alpine "sh" 4 seconds ago Up 3 seconds shared-container287be9c1c76b alpine "sh" 16 seconds ago Up 14 seconds prod-containerFinally, let’s also connect prod-container to a shared network:
admin@myhome:~$ docker network connect shared-network prod-containerAfter that, we can get a shell inside prod-container and ping shared-container:
admin@myhome:~$ docker exec -it prod-container /bin/sh/ # ping shared-containerPING shared-container (172.24.0.2): 56 data bytes64 bytes from 172.24.0.2: seq=0 ttl=64 time=0.267 ms64 bytes from 172.24.0.2: seq=1 ttl=64 time=0.171 ms^C--- shared-container ping statistics ---2 packets transmitted, 2 packets received, 0% packet lossround-trip min/avg/max = 0.171/0.219/0.267 ms/ # ping prod-containerPING prod-container (172.23.0.2): 56 data bytes64 bytes from 172.23.0.2: seq=0 ttl=64 time=0.167 ms64 bytes from 172.23.0.2: seq=1 ttl=64 time=0.410 ms64 bytes from 172.23.0.2: seq=2 ttl=64 time=0.108 ms^C5 packets transmitted, 5 packets received, 0% packet lossround-trip min/avg/max = 0.108/0.188/0.410 msYou can learn more about networking in Docker on the official website: https://docs.docker.com/network/.
Security features of Docker
Section titled “Security features of Docker”Docker, at its core, wasn’t meant to be a security tool. This was built in at a later stage with the support of the Linux Kernel features that are still being developed, and more security features are being added.
There’s a lot to cover regarding this topic, but we’re going to focus on the four most frequently used security features:
- Namespaces
- Security computing mode (seccomp)
- Rootless mode
- Docker signed images
Linux kernel namespaces
Section titled “Linux kernel namespaces”Kernel namespaces are an important component of Docker security as they provide isolation between containers and the host system. They allow each container to have a view of the system resources, such as the filesystem, network, and process table, without affecting the host or other containers. This means that a process running inside a container cannot access or modify the host filesystem, network configuration, or processes, which helps secure the host system from malicious or rogue containers.
Docker uses several Linux kernel namespaces to provide isolated environments for containers. These namespaces are used to create isolated environments for processes, networks, mount points, and more.
The USER namespace for the Docker daemon will ensure that the root inside the Docker container is running in a separate context from the host context. It’s needed to ensure that the root user inside the container is not equal to the root on the host.
The PID namespace isolates the process IDs between containers. Each container sees its own set of processes, isolated from other containers and the host.
The NET namespace’s function is to isolate the network stack of each container so that each container has a virtual network stack, with its own network devices, IP addresses, and routes.
The IPC namespace deals with the inter-process communication (IPC) resources between containers. Each container has its own private IPC resources, such as System V IPC objects, semaphores, and message queues.
The UTS namespace is about hostname and domain name isolation for each container. Here, each container has its own hostname and domain name that does not affect other containers or the host.
Finally, the MNT namespace isolates the mount points of each container. This means that each container has a private filesystem hierarchy, with its own root filesystem, mounted filesystems, and bind mounts.
By using these namespaces, Docker containers are isolated from each other and from the host, which helps ensure the security of containers and the host system.
The most confusing to use is the USER namespace as it requires a special UID and GID mapping configuration. It’s not enabled by default as sharing PID or NET namespaces with the host (–pid=host or –network=host) isn’t possible. Also, using the –privileged mode flag on docker run will not be possible without specifying –userns=host (thus disabling the USER namespace separation). Other namespaces listed previously are in effect mostly without any other special configuration.
Seccomp
Section titled “Seccomp”Seccomp, short for secure computing mode, is a Linux kernel feature that allows a process to specify the system calls it is allowed to make. This makes it possible to restrict the types of system calls that can be made by a container, which can help improve the security of the host system by reducing the risk of container escape or privilege escalation.
When a process specifies its seccomp profile, the Linux kernel filters incoming system calls and only allows those that are specified in the profile. This means that even if an attacker were to gain access to a container, they would be limited in the types of actions they could perform, reducing the impact of the attack.
To create a seccomp profile for a container, you can use the seccomp configuration option in the docker run command. This allows you to specify the seccomp profile to use when starting the container.
There are two main ways to create a seccomp profile: using a predefined profile or creating a custom profile. Predefined profiles are available for common use cases and can be easily specified in the docker run command. For example, the default profile allows all system calls, while the restricted profile only allows a limited set of system calls that are considered safe for most use cases.
To create a custom seccomp profile, you can use the Podman (https://podman.io/blogs/2019/10/15/generate-seccomp-profiles.html) or seccomp-gen (https://github.com/blacktop/seccomp-gen) tools. Both tools automate figuring out which calls are being made by the container you intend to use in production and generate a JSON file that can be used as the seccomp profile.
Seccomp does not guarantee security. It is important to understand the system calls that are required for your application and ensure that they are allowed in the seccomp profile.
The following is an example of a seccomp profile that allows a limited set of system calls for a container running a web server application:
{ "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { "name": "accept", "action": "SCMP_ACT_ALLOW" }, { "name": "bind", "action": "SCMP_ACT_ALLOW" }, { "name": "connect", "action": "SCMP_ACT_ALLOW" }, { "name": "listen", "action": "SCMP_ACT_ALLOW" }, { "name": "sendto", "action": "SCMP_ACT_ALLOW" }, { "name": "recvfrom", "action": "SCMP_ACT_ALLOW" }, { "name": "read", "action": "SCMP_ACT_ALLOW" }, { "name": "write", "action": "SCMP_ACT_ALLOW" } ]}In this example, defaultAction is set to SCMP_ACT_ALLOW, which means that all system calls not specifically listed in the syscalls array will be allowed. To block all not-defined calls, you can use SCMP_ACT_ERRNO as a default action. All available actions are described in the online manual for the seccomp_rule_add filter specification: https://man7.org/linux/man-pages/man3/seccomp_rule_add.3.html.
The syscalls array lists the system calls that should be allowed for the container and specifies the action to take for each call (in this case, all calls are allowed). This profile only allows the system calls necessary for a web server to function and blocks all other system calls, improving the security of the container.
More information about system calls is available here: https://docs.docker.com/engine/security/seccomp/.
Rootless mode
Section titled “Rootless mode”Docker Rootless mode is a feature that allows users to run Docker containers without having to run the Docker daemon as the root user. This mode provides an additional layer of security by reducing the attack surface of the host system and minimizing the risk of privilege escalation.
Let’s set up a rootless Docker daemon on Ubuntu Linux or Debian Linux. First, make sure you’ve installed Docker from the official Docker package repository instead of the Ubuntu/Debian package:
admin@myhome:~$ sudo apt-get install -y -qq apt-transport-https ca-certificates curladmin@myhome:~$ sudo mkdir -p /etc/apt/keyrings && sudo chmod -R 0755 /etc/apt/keyringsadmin@myhome:~$ curl -fsSL "https://download.docker.com/linux/ubuntu/gpg" | sudo gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpgadmin@myhome:~$ sudo chmod a+r /etc/apt/keyrings/docker.gpgadmin@myhome:~$ echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu jammy stable" | sudo tee /etc/apt/sources.list.d/docker.listadmin@myhome:~$ sudo apt-get updateadmin@myhome:~$ sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-scan-plugin docker-compose-plugin docker-ce-rootless-extras docker-buildx-plugindocker-ce-rootless-extras will install a shell script in your /usr/bin directory named dockerd-rootless-setuptool.sh, which will automate the whole process:
admin@myhome~$ dockerd-rootless-setuptool.sh --helpUsage: /usr/bin/dockerd-rootless-setuptool.sh [OPTIONS] COMMANDA setup tool for Rootless Docker (dockerd-rootless.sh).Documentation: https://docs.docker.com/go/rootless/Options: -f, --force Ignore rootful Docker (/var/run/docker.sock) --skip-iptables Ignore missing iptablesCommands: check Check prerequisites install Install systemd unit (if systemd is available) and show how to manage the service uninstall Uninstall systemd unitTo run this script, we will need a non-root user with a configured environment to be able to run the Docker daemon. Let’s create a dockeruser user first:
admin@myhome~$ sudo adduser dockeruserAdding user \`dockeruser' ...Adding new group \`dockeruser' (1001) ...Adding new user \`dockeruser' (1001) with group \`dockeruser' ...Creating home directory \`/home/dockeruser' ...Copying files from \`/etc/skel' ...New password:Retype new password:passwd: password updated successfullyChanging the user information for dockeruserEnter the new value, or press ENTER for the default Full Name []: Room Number []: Work Phone []: Home Phone []: Other []:Is the information correct? [Y/n] yLet’s also create a UID map configuration before we proceed. To do that, we will need to install the uidmap package and create the /etc/subuid and /etc/subgid configuration files:
admin@myhome~$ sudo apt install -y uidmapadmin@myhome~$ echo "dockeruser:100000:65536" | sudo tee /etc/subuidadmin@myhome~$ echo "dockeruser:100000:65536" | sudo tee /etc/subgidLog in as dockeruser and run the dockerd-rootless-setuptool.sh script:
admin@myhome~$ sudo -i -u dockeruserMake sure environment XDG_RUNTIME_DIR is set and systemd can read environment variables from dockeruser:
$ export XDG_RUNTIME_DIR=/run/user/$UID$ echo 'export XDG_RUNTIME_DIR=/run/user/$UID' >> ~/.bashrc$ systemctl --user show-environmentHOME=/home/dockeruserLANG=en_US.UTF-8LOGNAME=dockeruserPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/binSHELL=/bin/bashSYSTEMD_EXEC_PID=720USER=dockeruserXDG_RUNTIME_DIR=/run/user/1001XDG_DATA_DIRS=/usr/local/share/:/usr/share/:/var/lib/snapd/desktopDBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1001/busNow, you can install rootless Docker using the dockerd-rootless-setuptool.sh script (some output has been truncated for readability):
$ dockerd-rootless-setuptool.sh install[INFO] Creating [condensed for brevity] Active: active (running) since Fri 2023-02-17 14:19:04 UTC; 3s ago+ DOCKER_HOST=unix:///run/user/1001/docker.sock /usr/bin/docker versionClient: Docker Engine - Community Version: 23.0.1[condensed for brevity]Server: Docker Engine - Community Engine: Version: 23.0.1 [condensed for brevity] rootlesskit: Version: 1.1.0 [condensed for brevity]+ systemctl --user enable docker.serviceCreated symlink /home/dockeruser/.config/systemd/user/default.target.wants/docker.service → /home/dockeruser/.config/systemd/user/docker.service.[INFO] Installed docker.service successfully.Now, let’s verify if we can use the Docker rootless daemon:
dockeruser@vagrant:~$ export DOCKER_HOST=unix:///run/user/1001/docker.sockdockeruser@vagrant:~$ docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESAt this point, we have a Docker daemon running as a dockeruser system user instead of root. We will be able to run all services we need the same way we would in a standard configuration. There are some exceptions, such as a Docker in Docker setup, which require further configuration.
More detailed information about rootless mode can be found at https://docs.docker.com/engine/security/rootless/.
Docker signed images
Section titled “Docker signed images”Docker signed images are a security measure that assures users that a Docker image has come from a trusted source and has not been tampered with. Docker uses a digital signature to sign images, which can be verified by Docker Engine to ensure that the image is exactly as it was when it was signed by the publisher.
Docker signed images can be verified by checking the public key of the signer from a trusted registry (such as Docker Hub). If the image is valid, Docker will allow you to pull and run the image locally.
The first step in signing a Docker image is to generate a signing key. A signing key is a pair of keys – a public key and a private key – that can be used to sign and verify Docker images. The private key should be kept safe and not shared with anyone, while the public key can be distributed to users who need to verify the signed images. To generate a signing key, you can use the docker trust key generate command:
admin@myhome:~/$ docker trust key generate devopsGenerating key for devops...Enter passphrase for new devops key with ID 6b6b768:Repeat passphrase for new devops key with ID 6b6b768:Successfully generated and loaded private key. Corresponding public key available: /home/admin/devops.pubRemember to use a strong password to secure the key from access. The private key will be saved in your home directory – for example, ~/.docker/trust/private. The name of the file will be hashed.
Once you have generated the signing key, the next step is to initialize the trust metadata for the image. The trust metadata contains information about the image, including the list of keys that are authorized to sign the image. To initialize the trust metadata, you can use the docker trust signer add command. Note that you need to be logged into the Docker registry you’re using (via the docker login command):
admin@myhome:~/$ docker trust signer add --key devops.pub private-registry.mycompany.tld/registries/pythonappsAdding signer "devops" to private-registry.mycompany.tld/registries/pythonapps/my-python-app...Initializing signed repository for private-registry.mycompany.tld/registries/pythonapps/my-python-app...You are about to create a new root signing key passphrase. This passphrasewill be used to protect the most sensitive key in your signing system. Pleasechoose a long, complex passphrase and be careful to keep the password and thekey file itself secure and backed up. It is highly recommended that you use apassword manager to generate the passphrase and keep it safe. There will be noway to recover this key. You can find the key in your config directory.Enter passphrase for new root key with ID a23d653:Repeat passphrase for new root key with ID a23d653:Enter passphrase for new repository key with ID de78215:Repeat passphrase for new repository key with ID de78215:Successfully initialized "private-registry.mycompany.tld/registries/pythonapps/my-python-app"Successfully added signer: devops to private-registry.mycompany.tld/registries/pythonapps/my-python-appYou can sign the image by using the docker trust sign command after a successful Docker image build and tagging it with your registry name. This command signs the image using the authorized keys in the trust metadata and pushes this information, along with your Docker image, to the registry:
admin@myhome:~/$ docker trust sign private-registry.mycompany.tld/registries/pythonapps/my-python-app:2.9BETASigning and pushing trust data for local image private-registry.mycompany.tld/registries/pythonapps/my-python-app:2.9BETA, may overwrite remote trust dataThe push refers to repository [private-registry.mycompany.tld/registries/pythonapps]c5ff2d88f679: Mounted from library/ubuntulatest: digest:sha256:41c1003bfccce22a81a49062ddb088ea6478eabea1457430e6235828298593e6 size: 529Signing and pushing trust metadataEnter passphrase for devops key with ID 6b6b768:Successfully signed private-registry.mycompany.tld/registries/pythonapps/my-python-app:2.9BETATo verify that your Docker image has been signed and with which key, you can use the docker trust inspect command:
admin@myhome:~/$ docker trust inspect --pretty private-registry.mycompany.tld/registries/pythonapps/my-python-app:2.9BETASignatures for private-registry.mycompany.tld/registries/pythonapps/my-python-app:2.9BETASIGNED TAG DIGEST SIGNERSlatest 41c1003bfccce22a81a49062ddb088ea6478eabea1457430e6235828298593e6 devopsList of signers and their keys for private-registry.mycompany.tld/registries/pythonapps/my-python-app:2.9BETASIGNER KEYSdevops 6b6b7688a444Administrative keys for private-registry.mycompany.tld/registries/pythonapps/my-python-app:2.9BETA Repository Key: de782153295086a2f13e432db342c879d8d8d9fdd55a77f685b79075a44a5c37 Root Key: c6d5d339c75b77121439a97e893bc68a804368a48d4fd167d4d9ba0114a7336bDocker Content Trust (DCT) is disabled by default in the Docker CLI, but you can enable it by setting the DOCKER_CONTENT_TRUST environment variable to 1. This will prevent Docker from downloading non-signed and verified images to local storage.
More detailed information about DCT can be found on an official website: https://docs.docker.com/engine/security/trust/.
Docker for CI/CD pipeline integration
Section titled “Docker for CI/CD pipeline integration”Continuous integration (CI) and continuous deployment (CD) are popular software development practices that aim to ensure that the software development process is streamlined and the quality of code is maintained.
CI refers to the practice of automatically building and testing code changes in a shared repository. CD is the next step after CI, where the code changes are automatically deployed to production or a staging environment.
Docker is a popular tool that’s used in CI/CD pipelines as it provides an efficient way to package and distribute applications. In this subsection, we will show you how to build and push a Docker image to AWS Elastic Container Registry (ECR) using GitHub Actions.
Let’s look at an example of how to set up a GitHub Action to build and push a Docker image to AWS ECR.
Create a new GitHub Actions workflow by creating a new file named main.yml in the .github/workflows directory of your repository. After adding and pushing it to the main branch, it’ll be available and triggered after any new push to this branch.
In the main.yml file, define the steps for the workflow, like so:
name: Build and Push Docker Imageon: push: branches: - mainenv: AWS_REGION: eu-central-1jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: ${{ env.AWS_REGION }} - name: Build Docker image uses: docker/build-push-action@v2 with: push: true tags: ${{ env.AWS_REGION }}/my-image:${{ env.GITHUB_SHA }} - name: Push Docker image to AWS ECR uses: aws-actions/amazon-ecr-push-action@v1 with: region: ${{ env.AWS_REGION }} registry-url: ${{ env.AWS_REGISTRY_URL }} tags: ${{ env.AWS_REGION }}/my-image:${{ env.GITHUB_SHA }}Replace the AWS_REGION and AWS_REGISTRY_URL environment variables with your specific values. You should also replace my-image with the name of your Docker image.
In your GitHub repository settings, create two secrets named AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY with the AWS credentials that have the necessary permissions to push to AWS ECR. Alternatively, you could use your own runner and AWS IAM role attached to the runner or GitHub OIDC, which will authenticate itself with the AWS account. You can find the relevant documentation here: https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services.
With these steps in place, your GitHub Action will now automatically build and push your Docker image to AWS ECR every time you push code changes to the main branch. After the push, you could trigger another process on the server side to evaluate and deploy a new Docker image to one of your environments without further manual interaction. This helps streamline your CI/CD pipeline and ensures that your code changes are deployed to production with confidence.
It’s also possible to integrate the same pipeline with GitLab or other CI/CD tools in a similar manner.
In this section, we’ve learned about some not-so-common use cases for containers, such as rootless mode, secure computing mode, networking advanced use cases, and how to start a debugging container. In the next section, we will focus on automating the process of setting up Docker containers even further and how to orchestrate it a bit better than manually starting containers one by one.
Docker Compose
Section titled “Docker Compose”Docker Compose is a console tool for running multiple containers using one command. It provides an easy way to manage and coordinate multiple containers, making it easier to build, test, and deploy complex applications. With Docker Compose, you can define your application’s services, networks, and volumes in a single YAML file, and then start and stop all services from the command line.
To use Docker Compose, you first need to define your application’s services in a docker-compose.yml file. This file should include information about the services you want to run, their configuration, and how they are connected. The file should also specify which Docker images to use for each service.
The docker-compose.yaml file is a central configuration file that’s used by Docker Compose to manage the deployment and running of applications. It is written in YAML syntax.
The structure of the docker-compose.yaml file is divided into several sections, each of which defines a different aspect of the deployment. The first section, version, specifies the version of the Docker Compose file format being used. The second section, services, defines the services that make up the application, including their image names, environment variables, ports, and other configuration options.
The services section is the most important part of the docker-compose.yaml file as it defines how the application is built, run, and connected. Each service is defined by its own set of key-value pairs, which specify its configuration options. For example, the image key is used to specify the name of the Docker image to be used for the service, while the ports key is used to specify the port mappings for the service.
The docker-compose.yaml file can also include other sections, such as volumes and networks, which allow you to define shared data storage and network configurations for your application. Overall, the docker-compose.yaml file provides a centralized, declarative way to define, configure, and run multi-container applications with Docker Compose. With its simple syntax and powerful features, it is a key tool for streamlining the development and deployment of complex applications.
Environment variables are key-value pairs that allow you to pass configuration information to your services when they are run. In the docker-compose.yaml file, environment variables can be specified using the environment key within the service definition.
One way to specify environment variables in the docker-compose.yaml file is to simply list them as key-value pairs within the environment section. Here’s an example:
version: '3'services: db: image: mariadb environment: MYSQL_ROOT_PASSWORD: example MYSQL_DATABASE: example_dbIn addition to specifying environment variables directly in the docker-compose.yaml file, you can store them in an external file and reference that file within the docker-compose.yaml file using the env_file key. Here’s an example:
version: '3'services: db: image: mariadb env_file: - db.envThe contents of the db.env file might look like this:
MYSQL_ROOT_PASSWORD=exampleMYSQL_DATABASE=example_dbBy using an external env_file key, you can keep sensitive information separate from your docker-compose.yaml file and easily manage environment variables across different environments.
As an example, consider a MariaDB Docker image. The MariaDB image requires several environment variables to be set to configure the database, such as MYSQL_ROOT_PASSWORD for the root password, MYSQL_DATABASE for the name of the default database, and others. These environment variables can be defined in the docker-compose.yaml file to configure the MariaDB service.
Let’s look at an example of using Docker Compose to set up a nginx container, a PHP-FPM container, a WordPress container, and a MySQL container. We’ll start by defining our services in the docker-compose.yml file and break it down into smaller blocks with comments:
version: '3'The preceding line defines the version of the Docker Compose file syntax. Next, we will define all Docker images to be run and interact with each other:
services: web: image: nginx:latest depends_on: - wordpress ports: - 80:80 volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf - wordpress:/var/www/html networks: - wordpressThis defines a component of our application stack named web. It will use a Docker image from Docker Hub named nginx with the latest tag. Here are some other important settings:
depends_on: This tells Docker Compose to start this component after thewordpressservice.ports: This forwards your host port to a Docker port; in this case, it’ll open port80on your computer and forward all incoming traffic to the same port inside the Docker image, the same way the–psetting does when starting a single Docker container using the command line.volumes: This setting is equivalent to the-voption in the Docker command-line tool, so it’ll mount anginx.conffile from the local directory to the/etc/nginx/conf.d/default.conffile inside a Docker image.wordpress:/var/www/html: This line will mount a Docker volume namedwordpressto the directory inside the Docker image. The volume will be defined ahead.networks: Here, we’re connecting this service to a Docker network namedwordpress, which is defined as follows:
wordpress: image: wordpress:php8.2-fpm-alpine depends_on: - db environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: example_user WORDPRESS_DB_NAME: example_database WORDPRESS_DB_PASSWORD: example_password restart: unless-stopped volumes: - wordpress:/var/www/html networks: - wordpressThe preceding service is very similar to a web service, with the following additions:
environment: This defines environment variables present inside the Docker image.restart: This configures the service so that it’s automatically restarted if the process stops working for some reason. Docker Compose will not attempt to restart this service if we’ve manually stopped it.depends_on: This server will only be started after thedbservice is up.
Let’s look at the db service:
db: image: mariadb:10.4 environment: MYSQL_ROOT_PASSWORD: example_password MYSQL_DATABASE: example_database MYSQL_USER: example_user MYSQL_PASSWORD: example_password restart: unless-stopped volumes: - dbdata:/var/lib/mysql networks: - wordpressThis service is setting up the MariaDB database so that it can store WordPress data. Note that all environment variables we can use for MariaDB or WordPress images are documented on their respective Docker Hub pages:
volumes: wordpress: dbdata:Here, we’re defining the Docker volumes we are using for WordPress and MariaDB. These are regular Docker volumes that are stored locally, but by installing Docker Engine plugins, those could be distributed filesystems, such as GlusterFS or MooseFS:
networks: wordpress: name: wordpress driver: bridgeFinally, we’re defining a wordpress network with a bridge driver that allows communication between all preceding services with isolation from the Docker images running on a machine you will run it on.
In the preceding example, in addition to the options already covered in this section, we have a services dependency (depends_on), which will allow us to force the order in which containers will be started.
The two volumes we’re defining (wordpress and dbdata) are used for data persistence. The wordpress volume is being used to host all WordPress files and it’s also mounted to the web container that is running the nginx web server. That way, the web server will be able to serve static files such as CSS, images, and JavaScript, as well as forward requests to the PHP-FPM server.
Here’s the nginx configuration, which uses fastcgi to connect to the WordPress container running the PHP-FPM daemon:
server { listen 80; listen [::]:80; index index.php index.htm index.html; server_name _; error_log /dev/stderr; access_log /dev/stdout; root /var/www/html; location / { try_files $uri $uri/ /index.php; } location ~ \.php$ { include fastcgi_params; fastcgi_intercept_errors on; fastcgi_pass wordpress:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires max; log_not_found off; }}With this docker-compose.yml file, you can start and stop all the services defined in the file by using the docker-compose up and docker-compose down commands, respectively. When you run docker-compose up, Docker will download the necessary images and start the containers, and you’ll be able to access your WordPress website at http://localhost.
docker-compose is a very useful tool for running applications that require multiple services in an easy and repeatable way. It’s most commonly used when running applications locally for development, but some organizations decide to use docker-compose in production systems where it serves its purpose.
It’s extremely rare if you can use a ready-made Docker image for local development or production. Using public images as a base for your customization is a practice applied in, dare we claim it, all organizations using Docker. With that in mind, in the next section, we will learn how to build Docker images using multi-stage builds and how to use each Dockerfile command properly.
Advanced Dockerfile techniques
Section titled “Advanced Dockerfile techniques”Dockerfiles are used to define how an application should be built inside a Docker container. We covered most of the available commands in Chapter 8. Here, we will introduce more advanced techniques, such as multi-stage builds or not-so-common ADD command uses.
Multi-stage build
Section titled “Multi-stage build”Multi-stage builds are a feature of Docker that allows you to use multiple Docker images to create a single final image. By creating multiple stages, you can separate the build process into distinct steps and reduce the size of the final image. Multi-stage builds are particularly useful when building complex applications that require multiple dependencies as they allow developers to keep the necessary dependencies in one stage and the application in another.
One example of using multi-stage builds with a Golang application involves creating two stages: one for building the application and one for running it. In the first stage, the Dockerfile pulls in the necessary dependencies and compiles the application code. In the second stage, only the compiled binary is copied over from the first stage, reducing the size of the final image. Here’s an example Dockerfile for a Golang application:
# Build stageFROM golang:alpine AS buildRUN apk add --no-cache gitWORKDIR /appCOPY . .RUN go mod downloadRUN go build -o /go/bin/app# Final stageFROM alpineCOPY --from=build /go/bin/app /go/bin/appEXPOSE 8080ENTRYPOINT ["/go/bin/app"]In the preceding example, the Dockerfile creates two stages. The first stage uses the golang:alpine image and installs the necessary dependencies. Then, it compiles the application and places the binary in the /go/bin/app directory. The second stage uses the smaller Alpine image and copies the binary from the first stage into the /go/bin/app directory. Finally, it sets the entry point to /go/bin/app.
ADD command use cases
Section titled “ADD command use cases”The ADD command in a Docker file is used to add files or directories to the Docker image. It works in the same way as COPY but with some additional features. We’ve talked about basic uses before, but there are other use cases too.
The second use case allows you to unpack files compressed with ZIP or TAR and gzip tools on the fly. While adding a compressed file to the image, the file will be uncompressed and all the files inside it will be extracted to the destination folder. Here’s an example:
ADD my-tar-file.tar.gz /appThe third way of using the ADD command is to copy a remote file from a URL to the Docker image. For example, to download a file named file.txt from a URL, https://yourdomain.tld/configurations/nginx.conf, and copy it to the nginx configuration directory, /etc/nginx, inside the Docker image, you can use the following ADD command:
ADD https://yourdomain.tld/configurations/nginx.conf /etc/nginx/nginx.confYou can also use a Git repository to add your code:
ADD --keep-git-dir=true https://github.com/your-user-or-organization/some-repo.git#main /app/codeTo clone a Git repository over SSH, you will need to allow the ssh command inside Docker to access a private key with access to the repository you’re trying to access. You can achieve this by adding a private key in a multi-stage build and removing it at the end of the stage where you’re cloning a repository. This is generally not recommended if you have a choice. You can do this more securely by using Docker secrets and mounting the secret while running the build.
Here’s an example of using ARG with a private key:
ARG SSH_PRIVATE_KEYRUN mkdir /root/.ssh/RUN echo "${SSH_PRIVATE_KEY}" > /root/.ssh/id_rsa# make sure your domain is acceptedRUN touch /root/.ssh/known_hostsRUN ssh-keyscan gitlab.com >> /root/.ssh/known_hostsRUN git clone [email protected]:your-user/your-repo.gitHere’s an example of using a Docker secret and a mount:
FROM python:3.9-alpineWORKDIR /appRUN --mount=type=secret,id=ssh_id_rsa,dst=~/id_rsa chmod 400 ~/id_rsa \ && ssh-agent bash -c 'ssh-add ~/id_rsa; git clone [email protected]:your-user/your-repo.git' && rm -f ~/id_rsa # Rest of the build process follows…In the preceding example, we’re assuming your private key isn’t protected by the password and your key is being saved in the ssh_id_rsa file.
The final way of using the ADD command is to extract a TAR archive from the host machine and copy its contents to the Docker image. For example, to extract a TAR archive named data.tar.gz from the host machine and copy its contents to the /data directory inside the Docker image, you can use the following ADD command:
ADD data.tar.gz /data/Secrets management
Section titled “Secrets management”Docker secrets management is an important aspect of building secure and reliable containerized applications.
Secrets are sensitive pieces of information that an application needs to function, but they should not be exposed to unauthorized users or processes. Examples of secrets include passwords, API keys, SSL certificates, and other authentication or authorization tokens. These secrets are often required by applications at runtime, but storing them in plaintext in code or configuration files can be a security risk.
Securing secrets is crucial to ensuring the security and reliability of applications. Leaking secrets can lead to data breaches, service disruptions, and other security incidents.
In the basic Docker setup, it’s only possible to provide secrets to a Docker image using environment variables, as we covered in Chapter 8. Docker also provides a built-in secrets management mechanism that allows you to securely store and manage secrets. However, it’s only available when Swarm mode needs to be enabled (we will get back to Swarm later in this chapter in the Docker orchestration section).
To make secrets available to applications running inside Docker, you can use the docker secret create command. For example, to create a secret for a MySQL database password, you can use the following command:
admin@myhome:~/$ echo "mysecretpassword" | docker secret create mysql_password -This command creates a secret named mysql_password with a value of mysecretpassword.
To use a secret in a service, you need to define the secret in the service configuration file. For example, to use the mysql_password secret in a service, you can define it in the docker-compose.yml file, as follows:
version: '3'services: db: image: mysql environment: MYSQL_ROOT_PASSWORD_FILE: /run/secrets/mysql_password secrets: - mysql_password volumes: - db_data:/var/lib/mysqlsecrets: mysql_password: external: truevolumes: db_data:In this configuration file, the mysql_password secret is defined in the secrets section, and the MYSQL_ROOT_PASSWORD_FILE environment variable is set to the path of the secret file, which is /run/secrets/mysql_password.
To deploy the service, you can use the docker stack deploy command. For example, to deploy the service defined in the docker-compose.yml file, you can use the following command:
admin@myhome:~/$ docker stack deploy -c docker-compose.yml myappHandling secrets with care is extremely important from a security perspective. The most common mistake is putting a secret directly inside a Docker image, environment file, or application configuration file that is committed into the Git repository. There are existing contingencies that prevent users from doing that (such as Dependabot in GitHub), but if they should fail, it’s extremely hard to remove them from the Git history afterward.
In this section, we covered how to handle different aspects of building a container and advanced build techniques. With this knowledge and with the use of Docker Compose, you will be able to build and run your application with a decent dose of automation. What if you have 10 of those applications? 100? Or even more?
In the next section, we will dig into clusters, which will automate things further and deploy your applications to multiple hosts simultaneously.
Docker orchestration
Section titled “Docker orchestration”In the world of containerization, orchestration is the process of automating deployment and managing and scaling your applications across multiple hosts. Orchestration solutions help simplify the management of containerized applications, increase availability, and improve scalability by providing a layer of abstraction that allows you to manage containers at a higher level, instead of manually managing individual containers.
Docker Swarm is a Docker-native clustering and orchestration tool that allows you to create and manage a cluster of Docker nodes, allowing users to deploy and manage Docker containers across a large number of hosts. Docker Swarm is an easy-to-use solution that comes built-in with Docker, making it a popular choice for those who are already familiar with Docker.
Kubernetes is an open source container orchestration platform that was originally developed by Google. Kubernetes allows you to deploy, scale, and manage containerized applications across multiple hosts, while also providing advanced features such as self-healing, automated rollouts, and rollbacks. Kubernetes is one of the most popular orchestration solutions in use today and is widely used in production environments.
OpenShift is a container application platform that is built on top of Kubernetes and it’s developed by Red Hat. This platform provides a complete solution for deploying, managing, and scaling containerized applications, with additional features such as built-in CI/CD pipelines, integrated monitoring, and automatic scaling. OpenShift is designed to be enterprise-grade, with features such as multi-tenancy and role-based access control (RBAC), making it a popular choice for large organizations that need to manage complex containerized environments.
There is a wide variety of orchestration solutions available, each with its strengths and weaknesses. The choice of which solution to use ultimately depends on your specific needs, but Docker Swarm, Kubernetes, and OpenShift are all popular choices that provide robust and reliable orchestration capabilities for containerized applications.
Docker Swarm
Section titled “Docker Swarm”Docker Swarm is a native clustering and orchestration solution for Docker containers. It provides a simple yet powerful way to manage and scale Dockerized applications across a cluster of hosts. With Docker Swarm, users can create and manage a swarm of Docker nodes that act as a single virtual system.
The base components of Docker Swarm are as follows:
- Nodes: These are the Docker hosts that form the Swarm. Nodes can be physical or virtual machines running the Docker daemon, and they can join or leave the Swarm as needed.
- Services: These are the applications that run on the Swarm. A service is a scalable unit of work that defines how many replicas of the application should run, and how to deploy and manage them across the Swarm.
- Managers: These are the nodes responsible for managing the Swarm state and orchestrating the deployment of services. Managers are in charge of maintaining the desired state of the services and ensuring they are running as intended.
- Workers: These are the nodes that run the actual containers. Workers receive instructions from the managers and run the desired replicas of the service.
- Overlay networks: These are the networks that allow the services to communicate with each other, regardless of the node they are running on. Overlay networks provide a transparent network that spans the entire Swarm.
Docker Swarm provides a simple and easy-to-use way to manage containerized applications. It is tightly integrated with the Docker ecosystem and provides a familiar interface for Docker users. With its built-in features for service discovery, load balancing, rolling updates, and scaling, Docker Swarm is a popular choice for organizations that are just starting with container orchestration.
To initialize Docker Swarm mode and add two workers to the cluster, you will need to initialize Swarm mode:
admin@myhome:~/$ docker swarm initSwarm initialized: current node (i050z7b0tjoew7hxlz419cd8l) is now a manager.To add a worker to this swarm, run the following command: docker swarm join --token SWMTKN-1-0hu2dmht259tb4skyetrpzl2qhxgeddij3bc1wof3jxh7febmd-6pzkhrh4ak345m8022hauviil 10.0.2.15:2377To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.This will create a new Swarm and make the current node the Swarm manager.
Once the Swarm has been initialized, you can add worker nodes to the cluster. To do this, you need to run the following command on each worker node:
admin@myhome:~/$ docker swarm join --token <token> <manager-ip>Here, <token> is the token generated by the docker swarm init command output, which you can find in the preceding code block, and <manager-ip> is the IP address of the Swarm manager.
For example, if the token is SWMTKN-1-0hu2dmht259tb4skyetrpzl2qhxgeddij3bc1wof3jxh7febmd-6pzkhrh4ak345m8022hauviil and the manager IP is 10.0.2.15, the command would be as follows:
admin@myhome:~/$ docker swarm join --token SWMTKN-1-0hu2dmht259tb4skyetrpzl2qhxgeddij3bc1wof3jxh7febmd-6pzkhrh4ak345m8022hauviil 10.0.2.15After running the docker swarm join command on each worker node, you can verify that they have joined the Swarm by running the following command on the Swarm manager node:
admin@myhome:~/$ docker node lsID HOSTNAME STATUS AVAILABILITY MANAGER STATUS ENGINE VERSIONi050z7b0tjoew7hxlz419cd8l * myhome Ready Active Leader 23.0.1This will show a list of all the nodes in the Swarm, including the manager and any workers you have added.
After that, you can add more nodes and start deploying applications to Docker Swarm. It’s possible to reuse any Docker Compose you’re using or Kubernetes manifests.
To deploy a sample application, we can reuse a Docker Compose template by deploying a wordpress service, but we will need to update it slightly by using MySQL user and password files in the environment variables:
wordpress: image: wordpress:php8.2-fpm-alpine depends_on: - db environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER_FILE: /run/secrets/mysql_user WORDPRESS_DB_NAME: example_database WORDPRESS_DB_PASSWORD_FILE: /run/secrets/mysql_passwordHere’s an example of adding secrets to both the wordpress and db services:
secrets: - mysql_user - mysql_passworddb: image: mariadb:10.4 environment: MYSQL_ROOT_PASSWORD: example_password MYSQL_DATABASE: example_database MYSQL_USER_FILE: /run/secrets/mysql_user MYSQL_PASSWORD_FILE: /run/secrets/mysql_passwordHere’s an example of adding a secrets definition at the bottom of docker-compose.yml:secrets:
mysql_user: external: truemysql_password: external: trueThe external: true setting is telling docker-compose that secrets are already present and that it should not try to update or recreate them on its own.
In this version of the Compose file, we use secrets to store the MySQL user and password for both the wordpress and db services.
To deploy this file to Docker Swarm, we can use the following commands:
admin@myhome:~/$ echo "root" | docker secret create mysql_user -vhjhswo2qg3bug9w7id08y34fecho "mysqlpwd" | docker secret create mysql_password -oy9hsbzmzrh0jrgjo6bgsydolThen, we can deploy the stack:
admin@myhome:~/$ docker stack deploy -c docker-compose.yml wordpressIgnoring unsupported options: restartCreating network wordpress_wordpressCreating service wordpress_webCreating service wordpress_wordpressCreating service wordpress_dbHere, docker-compose.yaml is the name of the Compose file and my-stack-name is the name of the Docker stack.
Once the stack has been deployed, the wordpress, web, and db services will be running with the MySQL user and password specified in the secrets. You can verify this by listing stacks and checking if containers are running:
admin@myhome:~/$ root@vagrant:~# docker stack lsNAME SERVICESwordpress 3root@vagrant:~# docker psCONTAINER ID IMAGE CREATED STATUS PORTS NAMES7ea803c289b0 mariadb:10.4 "docker-entrypoint.s…" 28 seconds ago Up 27 seconds 3306/tcp wordpress_db.1.dogyh5rf52zzsiq0t95nrhuhced25de3273a2 wordpress:php8.2-fpm-alpine "docker-entrypoint.s…" 33 seconds ago Up 31 seconds 9000/tcp wordpress_wordpress.1.xmmljnd640ff9xs1249jpym45Docker Swarm is a great project to start your adventure with Docker orchestration methods. It’s possible to use it with a production-grade system by using various plugins that will extend its default functionality.
Kubernetes and OpenShift
Section titled “Kubernetes and OpenShift”Two of the most popular tools for orchestrating Docker containers are Kubernetes and OpenShift. Although they share some similarities, they also have some significant differences. Here are the main differences between Kubernetes and OpenShift:
- Architecture: Kubernetes is a standalone orchestration platform that is designed to work with multiple container runtimes, including Docker. OpenShift, on the other hand, is a platform that is built on top of Kubernetes. It provides additional features and tools, such as source code management, continuous integration, and deployment. These additional features make OpenShift a more comprehensive solution for enterprises that require end-to-end DevOps capabilities.
- Ease of use: Kubernetes is a powerful orchestration tool that requires a high level of technical expertise to set up and operate. OpenShift, on the other hand, is designed to be more user-friendly and accessible to developers with varying levels of technical knowledge. OpenShift provides a web-based interface for managing applications and can be integrated with various development tools, making it easier for developers to work with.
- Cost: Kubernetes is an open source project that is free to use, but enterprises may need to invest in additional tools and resources to set it up and operate it. OpenShift is an enterprise platform that requires a subscription for full access to its features and support. The cost of OpenShift may be higher than Kubernetes, but it provides additional features and support that may be worth the investment for enterprises that require advanced DevOps capabilities.
Both solutions are powerful Docker orchestration tools that offer different benefits and trade-offs. Kubernetes is highly customizable and suitable for more technical users. OpenShift, on the other hand, provides a more comprehensive solution with additional features and a user-friendly interface but comes at a higher cost. You should consider specific needs in your organization when choosing between these two tools, keeping in mind that Docker Swarm is also an option. Cloud providers also developed their own solutions, with Elastic Container Service being one of them.
Summary
Section titled “Summary”In this chapter, we covered more advanced topics around Docker, only touching topics around orchestration. Kubernetes, OpenShift, and SaaS solutions provided by cloud operators are driving the creation of new tools that will further ease Docker’s use in modern applications.
Docker has had a profound impact on the world of software development and deployment, enabling us to build, ship, and run applications more efficiently and reliably than ever before. By understanding the internals of Docker and following best practices for working with it, we can ensure that our applications are secure, performant, and scalable across a wide range of environments.
In the next chapter, we will look into challenges on how to monitor and gather logs in a distributed environment built on top of Docker containers.