Docker Basics
local graph
Chapter 8 — Docker Basics
Section titled “Chapter 8 — Docker Basics”In this chapter, we introduce one of the building blocks of the DevOps toolkit – containers. We are going to explain the differences between virtualization and containers, and then present the advantages and disadvantages of both solutions. Additionally, we are going to present a way to choose between both solutions for a given workload.
The main topics covered in this chapter are as follows:
- Virtualization versus containerization
- Anatomy of Docker
- Docker commands
- Dockerfile
- Docker image registries
- Docker networking
Technical requirements
Section titled “Technical requirements”For this chapter, you will need a Linux system with an installed Docker Engine. We are not going to cover the installation steps here. Different Linux distributions provide Docker in different ways. We are going to use Docker Engine 20.10.23 here. Since in this chapter all examples are very basic, older versions of Docker will most probably work. Still, if you run into issues with following our examples, updating Docker to our version should be your first step in troubleshooting.
Virtualization versus containerization
Section titled “Virtualization versus containerization”In this section, we are going to explain what virtualization and containerization are and what the major differences between them are.
Virtualization
Section titled “Virtualization”Virtualization is a technique of running a complete simulated computer within another computer. Complete means that it mirrors everything a physical computer would have: motherboard, BIOS, processor, hard drives, USB ports, and so on. Simulated means that it is entirely a product of software. This computer does not exist physically, thus it is called virtual. To exist, the virtual machine (VM), as simulated computers are often called, needs a real, physical one to emulate it. The physical machine is called a host or hypervisor.
So, I have a physical computer. It is powerful. Why would I want to run a VM in it? For obvious reasons, the VM will be less powerful than the host: after all, the host requires RAM, CPU, and hard drive space for itself. There is also some small drop in performance (since we are actually running a program that emulates full hardware) when compared to the physical machine.
The reasons can vary depending on the use case, but there are a lot of them.
You may want to run a full operating system different from your own to test some software, to run software unavailable for your operating system, or to dutifully recreate a development environment for your application. You may want to recreate, as closely as possible, a production environment for your application. All those are valid and pretty popular reasons for using VMs.
Let us see what the advantages of virtualization are:
- Isolation: VMs present themselves, as mentioned, as fully functional computers. To the running operating system, they create the illusion of being separate physical machines. Whatever we run in them shouldn’t be able to access the host computer (unless specifically allowed to) and, indeed, barring a few incidents where such things were possible (as a result of a programming error), VMs have provided secure environments. This isolation is a very good solution in malware analysis, running workloads that require separate servers, and so on. As an example, if a VM runs a single WWW server, the security vulnerability in the server may grant the attacker access to the operating system, thus allowing them a free run. But since other components of infrastructure, for example, databases, are run in separate VMs, the incident can be contained to the WWW server only.
- Tuning: With a sufficiently powerful host, it is possible to partition its resources so that each running VM has guaranteed RAM, hard disk space, and CPU.
- Operating system simplification: When running various workloads, such as databases, WWW servers, and mail servers, the complexity of maintaining a single server running them all grows pretty fast. Every installed software requires additional software to be installed (such as libraries and helper programs). Libraries required by various programs may introduce incompatibilities (especially if we install software not distributed by operating system developers, so-called third-party programs). On rare occasions, even the software included in the distribution may be incompatible with each other to a degree that makes it impossible or very difficult to install them on one operating system. Maintenance of such a system can become troublesome and require a lot of detective work. Modern hypervisor software alleviates many system administration hurdles by means of clones, snapshots, golden images, and so on.
- Automation: Modern virtualization software provides a lot of features that promote the automation of system management on many levels. Snapshots – a point-in-time capture of the whole system – allow a rollback at any given moment to a previous system state. This allows it to easily back out of unwanted changes to the last known good state. Clones let us provision new VMs based on another, already running and configured. Golden images are archived images of VMs that we can easily and quickly import and start – completely omitting installation and limiting configuration to the absolute minimum. This also allows for reliable environment recreation.
- Speed up: Properly setting up a workflow utilizing VMs allows us to start a new operating system complete with its own server or desktop hardware in a matter of minutes instead of hours. This opens new possibilities for testing environments, remote desktop solutions, and so on.
The preceding list is not exhaustive but should easily demonstrate why virtualization became a darling of data centers and hosting companies. The availability of a wide variety of servers we can cheaply rent is a direct result of virtualization allowing companies to partition the hardware.
As great as the solution is, it is not a panacea and not everything should be virtualized. More so, running a separate VM for every piece of software easily leads to resource utilization overhead. 100 virtual servers not only will use the CPU and RAM provided to the operating system in it but also, some percent will be used for housekeeping on the host machine. Each of those servers will utilize the disk space required by the operating system within, even though it probably will be an exact copy of the 99 other servers on the same server – a waste of space, RAM, and CPU. Also, bringing up a new VM will take some time. Granted, if you have everything configured and automated properly, it is going to be shorter than setting up a new hardware machine, but still.
Before virtualization became widely available, operating system developers were trying to provide techniques that would allow system operators to isolate various workloads. The main targets were data centers, where one physical server was too much for one workload (a database or a WWW server), but running more than one posed a risk (security, stability, etc.). After the virtualization became widespread, it became obvious that using it was sometimes like using cannons against sparrows. It doesn’t make sense to procure a whole new server (even virtual) with the whole operating system when you want to run a small program. Thus, through a natural progression of innovating new features that allow for better process isolation, containers arose.
Containerization
Section titled “Containerization”Containers are lightweight virtual environments that allow us to run a single process in an isolated manner. An ideally prepared container consists of only software and libraries required to run the application. The host operating system takes care of operating hardware, managing memory, and all other peripheral tasks. The main assumption of the container is that it doesn’t emulate being a separate operating system or a separate server. Processes or users within the container can easily find out they are enclosed there. The downside is that containers won’t emulate hardware. You cannot use them to test new drivers, for instance. The upside is that a single container can take as little as just a few megabytes of hard drive space and only the memory required for the process to run.
As a consequence, starting up a container takes only the time that the application needs to start. The bootup time – the BIOS, hardware tests, and operating system boot time – is all shaved off. All the software not required by the application can, and should, be omitted. Given the small size of container images, their redistribution times became almost negligible, their start times almost instantaneous, and the build time and process largely simplified. This has led to much easier recreation of the environment. This, in turn, has led to easier test environment setup and very often deployments of new versions of the software – as often as several thousand times a day. The scaling of applications has become much easier and faster.
The preceding brought another change in the approach to running applications. The logical consequence of the preceding change is that containers are not maintained the same way the operating system is. You do not upgrade software within the container – you deploy a container with a new version of software in place of the obsolete one. This leads to an assumption that you don’t keep data within a container but in a filesystem that you attach to the container during the run.
The poster child of Linux containerization is Docker. One thing that Docker did that has probably helped to bring the revolution is creating an ecosystem for easy sharing of container images.
A container image is, in the case of Docker, a simple archive consisting of all the binaries and libraries that are required for the application and a few files with configuration information. Since the size tends to be rather small and the image never has any data within, it is logical to allow people to share the image they have built. Docker has an image hub (called Docker Hub) with a nice WWW UI, and command-line tools for searching, downloading, and uploading images. The hub allows rating images and giving comments and feedback to the authors.
Now that we know what containerization is, we can look deeper into how Docker works internally and what makes it tick. Let’s look into the anatomy of Docker.
Anatomy of Docker
Section titled “Anatomy of Docker”Docker comprises several components:
- Command-line utility – Docker
- Host
- Objects
- Registries
The Docker CLI tool – docker – is the main means of managing containers and images. It is used to build images, pull them from the registry, upload them to the registry, run containers, interact with them, set runtime options, and, finally, destroy them. It is a command-line tool that communicates with Docker hosts using an API. By default, it is assumed that the docker command is being invoked on the host, but it is not strictly necessary. One docker CLI tool can manage more than one host.
The host is more interesting. The host runs dockerd – a daemon responsible for actually performing the actions ordered via the docker tool. It is here that container images are stored. The host also provides resources such as networking, storage, and the containers themselves.
The dockerd daemon is the beating heart of the containers. It’s the background process that runs on a host machine and manages the containers. dockerd manages creating and managing containers, providing an API for interacting with the daemon, managing volumes, networks, and image distribution, providing an interface to manage images and containers, and storing and managing metadata for containers and images. It also manages communication between other processes in Docker Swarm mode.
OverlayFS
Section titled “OverlayFS”OverlayFS was first released as a part of the Linux kernel version 3.18 in August 2014. It was initially developed as a means to provide a more efficient and flexible way to handle container storage in comparison to the previous storage driver, Another UnionFS (AUFS). OverlayFS was considered the next generation of UnionFS, which was the storage driver used by Docker at that time.
This filesystem was included as a built-in storage driver in Docker starting from version 1.9.0. Since then, OverlayFS has become the default storage driver for Docker on most Linux distributions, and it is widely used in various container orchestration platforms such as Kubernetes and OpenShift.
OverlayFS is a filesystem for Linux that allows for the overlay of one directory on top of another. It allows for the creation of a virtual filesystem that is composed of two different directories: a lower directory and an upper directory. The upper directory contains the files that are visible to the user, while the lower directory contains the base files that are hidden.
When a file or directory is accessed in the upper directory, OverlayFS first looks for it in the upper directory, and if it doesn’t find it, it looks in the lower directory. If the file or directory is found in the upper directory, that version is used. If it is found in the lower directory, that version is used.
This mechanism allows for the creation of overlay filesystems, where the upper directory can be used to add, modify, or delete files and directories in the lower directory, without modifying the lower directory itself. This is useful in scenarios such as containerization, where the upper layer can be used to store the changes made in a container, while the lower layer contains the base image for the container.
What is an image?
Section titled “What is an image?”A Docker image is a pre-built package that contains all of the files and settings needed to run a piece of software in a container. It includes your application code or a binary, runtime, system tools, libraries, and all needed configuration files. Once an image is built, it can be used to start one or more containers, which are isolated environments that provide a consistent way to run the software.
When starting a container, you must select a program to run as a primary process of the container. If this process quits, the whole container will be terminated as well.
Building a Docker image typically involves creating a Dockerfile, which is a script that contains instructions for building the image. The Dockerfile specifies the base image to use, any additional software to be installed, any files to be added to the image, and any configuration settings to be applied.
When building an image, Docker reads the instructions in the Dockerfile and performs the steps we’ve prepared inside the Dockerfile.
Once the image is built, it can be saved and used to start one or more containers. The process of building an image can also be automated using a tool such as Jenkins, GitHub, or GitLab actions, which can automatically build and test new images whenever changes are made to the code base.
The resulting image consists of a unique ID (SHA-256 hash), which is a hash of the image’s content and metadata, and it also can have a tag, which is a human-readable string that can be used to refer to a specific version of the image. UnionFS takes care of merging all content when running a container.
To inspect the metadata and content parts of an image, you can run the following commands:
admin@myhome:~$ docker pull ubuntuadmin@myhome:~$ docker inspect ubuntu[ { "Id": "sha256:6b7dfa7e8fdbe18ad425dd965a1049d984f31cf0ad57fa6d5377cca355e65f03", "RepoTags": [ "ubuntu:latest" ], "RepoDigests": [ "ubuntu@sha256:27cb6e6ccef575a4698b66f5de06c7ecd61589132d5a91d098f7f3f9285415a9" ], "Created": "2022-12-09T01:20:31.321639501Z", "Container": "8bf713004e88c9bc4d60fe0527a509636598e73e3ad1e71a9c9123c863c17c31", "Image": sha256:070606cf58d59117ddc1c48c0af233d6761addbcd4bf9e8e39fd10eef13c1bb7", "GraphDriver": { "Data": { "MergedDir": "/var/lib/docker/overlay2/f2c75e37be7af790f0823f6e576ec511396582ba71defe5a3ad0f661a632f11e/merged", "UpperDir": "/var/lib/docker/overlay2/f2c75e37be7af790f0823f6e576ec511396582ba71defe5a3ad0f661a632f11e/diff", "WorkDir": "/var/lib/docker/overlay2/f2c75e37be7af790f0823f6e576ec511396582ba71defe5a3ad0f661a632f11e/work" }, "Name": "overlay2" }, "RootFS": { "Type": "layers", "Layers": ["sha256:6515074984c6f8bb1b8a9962c8fb5f310fc85e70b04c88442a3939c026dbfad3" ] }, }]There’s a lot of information here, so we’ve stripped the output and left the information we want to focus on. You can see an image ID, all merged directories under the GraphDriver section, and the RootFS sha256 layer. RootFS contains the whole filesystem created by UnionFS when we start a process within the container.
What is a container runtime?
Section titled “What is a container runtime?”A container runtime (or container engine) is a software component that runs containers on your system. Container runtimes load container images from a Docker registry, monitoring system resources, allocating system resources for a container, and managing its life cycle.
There are a number of runtime containers that are being used. The most known and used on laptops – you probably have it installed on your system already – is containerd. It’s a high-performance container runtime that is designed to be embedded in a larger system. It is used by many cloud providers and is also the default runtime for Kubernetes.
LXC is a runtime that uses Linux namespaces and cgroups to provide isolation for containers. It is considered to be more lightweight and efficient than Docker (containerd). It’s also harder to use.
Another interesting runtime is Container Runtime Interface for OCI (CRI-O). CRI-O is fully compliant with the Open Container Initiative (OCI) specification, which means that it can run any OCI-compliant container image. Also, it’s designed to work natively with Kubernetes Pods, which allows it to provide better integration with Kubernetes than other runtimes.
Rocket (rkt) is an alternative container runtime that is designed to be more secure and efficient than Docker. It uses the App Container (appc) image format and has a simpler architecture than Docker. It’s also not used very often.
Other container engines worth noting are run Open Container (runC), a low-level container engine that provides the basic functionality for creating and managing containers, and Firecracker developed by AWS.
cgroups
Section titled “cgroups”Linux cgroups (short for control groups) are a Linux kernel feature that allows for the management and isolation of system resources for groups of processes. Cgroups allow the system administrator to allocate resources such as CPU, memory, and network bandwidth to specific groups of processes, and to monitor and control their usage.
This can be used to limit the resources used by a particular application or user, or for isolating different types of workloads on a shared system.
Docker by default doesn’t limit either CPU or memory consumption for an application inside a container. It’s quite easy to enable without any direct interaction with cgroups or kernel settings – the Docker daemon will do it for us.
You can limit the amount of memory a Docker container can use by using the --memory or -m option with the docker run command.
For example, use the following to run the alpine image with a memory limit of 500 MB:
admin@myhome:~$ docker run --memory 500m alpine /bin/shYou can specify the memory limit in bytes, kilobytes, megabytes, or gigabytes by using the appropriate suffix (b, k, m, or g).
When you limit the memory for a container, Docker will also limit the amount of memory swap that a container can use. By default, the memory swap limit is twice the value of the memory limit. It’s also possible to limit the memory swap by using the --memory-swap or -- memory-swappiness option.
Limiting usage of the CPU time that an application inside a Docker container can use can be done by using the CPU shares limit (--cpus or -c option). CPU shares are a relative measure of CPU time that a container can use. By default, a container is allocated a certain number of CPU shares, which it can use to consume CPU time proportional to its share. For example, if a container has 0.5 CPU shares, it can use up to 50% of the CPU time if no other containers are consuming CPU.
Other options available are the following:
--cpuset-cpus: This allows you to specify the range of CPU cores that the container can use, for example,0-1to use the first two cores, or0,2to use the first and third core.--cpu-shares: This allows you to set a CPU time limit for a Docker container. It specifies the amount of CPU time, in microseconds, that the container can use in a given period of time. The period of time is specified by the--cpu-periodoption.--cpu-quotaand--cpu-period:--cpu-quotais the CPU time limit in microseconds and--cpu-periodis the length of the CPU time period in microseconds.
The --cpu-quota and --cpu-period options allow you to specify a more precise CPU time limit for a container compared to the --cpus and --cpuset-cpus options. It is useful if you need to limit the CPU time for a container more precisely to prevent performance issues or ensure that your application runs reliably.
In this section, we went through the container runtime and how it works. Next, we will be looking into the command-line interface for the containerd daemon to interact with all Docker components in an easy and robust way.
Docker commands
Section titled “Docker commands”The Docker command-line interface is a tool that allows users to interact with containers. It provides a set of commands that you can use to build Docker images and create and manage containers, images, networks, and volumes. It interacts with the containerd daemon using a socket file or network.
The most common commands you can use are the following:
build: This allows you to build a new Docker image using a Dockerfilerun: This starts a new containerstart: This restarts one or more stopped containersstop: This will stop one or more running containerslogin: This is used to gain access to private registriespull: This downloads an image or a repository from a registrypush: This uploads an image or a repository to a registrybuild: This helps create an image from a provided Dockerfileimages: This lists all images on your machineps: This lists all running containersexec: This executes a command in a running containerlogs: This shows the logs of a containerrm: This removes one or more containersrmi: This removes one or more imagesnetwork: This is used to manage Docker networksvolume: This is used to manage volumes
docker build
Section titled “docker build”The docker build command is used to build a Docker image from a Dockerfile. The basic syntax is as follows:
docker build [OPTIONS] PATH | URL | -PATH is the path to the directory containing the Dockerfile.
URL is the URL to a Git repository containing the Dockerfile.
- (a dash) is used to build an image from the contents of stdin, so you could pipe Dockerfile content to it from the output of some previous command that would build a Dockerfile, for example, generate it from a template.
To build an image from a Dockerfile located in the current directory, you would run the following command:
admin@myhome:~$ docker build .You can also use a specific tag for the build image, as in the following example:
admin@myhome:~$ docker build -t my-image:1.0 .You can also pass --build-arg to your build command to pass build-time variables to the Dockerfile:
admin@myhome:~$ docker build --build-arg VAR1=value1 -t my-image:1.0 .docker run
Section titled “docker run”When you’re running a container, you’re essentially taking a Docker image and executing a process within that environment. An image is a blueprint or a snapshot of a container; it’s a read-only template with instructions for creating a container. A container that is running is an instance of that image but with its own state.
The docker run command is used to start a container from a Docker image. For example, to start a container from the myimage image and run /bin/bash, you would run the following command:
admin@myhome:~$ docker run myimage /bin/bashYou can also pass options to the run command, as in the following example:
admin@myhome:~$ docker run -d -p 8080:80 --name containername myimageThis command starts the container in detached mode (the -d option; it puts a container in the background), maps port 80 in the container to port 8080 on the host (-p 8080:80), and assigns the name containername to the container (-- name containername).
You can also pass environment variables to the container:
admin@myhome:~$ docker run -e VAR1=value1 -e VAR2=value2 myimage:latestDocker containers don’t store data after they are killed. To make data persistent you would use storage external to the docker container itself. In the simplest setup, this would be a directory or a file on filesystem outside the container.
There are two ways to do it: create a Docker volume:
admin@myhome:~$ docker volume create myvolumeTo use this volume for data persistence you’d mount it when starting the container:
admin@myhome:~$ docker run –v myvolume:/mnt/volume myimage:latestYou can also bind mount local folder (bind mount is a Docker term for this operation) as a volume inside the container using the -v option. In this case you don’t run the Docker volume create command:
admin@myhome:~$ docker run -v /host/path:/mnt/volume myimage:latestYou can also specify the working directory inside the container using the - w option:
admin@myhome:~$ docker run -w /opt/srv my-imageOther options that are useful are as follows:
--rm: This option will remove the container after it is stopped-P,--publish-all: This option will publish all exposed ports (EXPOSEoption inDockerfile) to a random local port--network: This option will connect the container to the Docker network specified
You can find more available options to use by invoking the docker run -- help command.
docker start
Section titled “docker start”The docker start command is used to start one or more stopped Docker containers. For example, to start a container, you would run the following command:
admin@myhome:~$ docker start mycontainermycontainer is the name or ID of the container you want to start. You can check all running and stopped containers using the docker ps command; we will get into it a bit later. You can also start multiple containers at once. To do that, you can list their names or IDs separated by spaces.
To start multiple containers, you would run the following command:
admin@myhome:~$ docker start mycontainer othercontainer lastcontainerTo attach to the container’s process so that you can see its output, use the -a option while starting the container:
admin@myhome:~$ docker start -a mycontainerdocker stop
Section titled “docker stop”This command is used to stop containers running in the background. The syntax for the command is the same as for starting the container. The difference lies in the available options you can use.
To stop multiple containers at once, you can list their names or IDs separated by spaces.
admin@myhome:~$ docker stop mycontainerTo stop multiple containers, you would run the following command:
admin@myhome:~$ docker stop mycontainer othercontainer lastcontainerYou can also use the -t option to specify the amount of time (in seconds) to wait for the container to stop before sending a SIGKILL signal. For example, to wait for 10 seconds before stopping a container, run the following:
admin@myhome:~$ docker stop -t 10 mycontainerYou can also use --time or -t to specify the amount of time to wait for the container to stop before sending a SIGKILL signal.
By default, the docker stop command sends a SIGTERM signal to the container, which gives the process running in the container a chance to cleanly shut down. If the container does not stop after the default 10-second timeout, a SIGKILL signal will be sent to force it to stop.
docker ps
Section titled “docker ps”This command is used to list the running or stopped containers. When you run the docker ps command without any options, it will show you the list of running containers along with their container ID, names, image, command, created time, and status:
admin@myhome:~$ docker psIt’s possible to view all containers with the - a option:
admin@myhome:~$ docker ps -aCONTAINER ID IMAGE COMMANDSTATUS PORTS NAMESa1e83e89948e ubuntu:latest "/bin/bash -c 'while…" 29 seconds ago Up 29 seconds pedantic_mayer0e17e9729e9c ubuntu:latest "bash" About a minute ago Exited (0) About a minute ago angry_stonebrakeraa3665f022a5 ecr.aws.com/pgsql/server:latest "/opt/pgsql/bin/nonr…" 5 weeks ago Exited (255) 8 days ago 0.0.0.0:1433->1433/tcp db-1You can use the --quiet or -q option to display only the container IDs, which might be useful for scripting:
admin@myhome:~$docker ps --quietYou can use the --filter or -f option to filter the output based on certain criteria:
admin@myhome:~$docker ps --filter "name=ubuntu"To inspect how much disk space the container is utilizing, you will need to use the - s option:
admin@myhome:~$ docker ps -sCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZEa1e83e89948e ubuntu:latest "/bin/bash -c 'while…" 14 seconds ago Up 13 seconds pedantic_mayer 0B (virtual 77.8MB)This container doesn’t use additional space on the disk, as it didn’t save any data.
docker login
Section titled “docker login”The docker login command is used to log in to a Docker registry. A registry is a place where you can store and distribute Docker images. The most commonly used registry is Docker Hub, but you can also use other registries, such as AWS Elastic Container Registry (ECR), Project Quay, or Google Container Registry.
By default, docker login will connect to the Docker Hub registry. If you want to log in to a different registry, you can specify the server URL as an argument:
admin@myhome:~$ docker login quay.ioWhen you run the docker login command, it will prompt you for your username and password. If you don’t have an account on the registry, you can create one by visiting the registry’s website.
Once you are logged in, you will be able to push and pull images from the registry.
You can also use the --username or -u option to specify your username, and --password or -p to specify the password on the command line, but it is not recommended due to security reasons.
You can also use the --password-stdin or -P option to pass your password via stdin:
admin@myhome:~$ echo "mypassword" | docker login --username myusername --password-stdinIt can be an output for any command. For example, to log in to AWS ECR, you would use the following command:
admin@myhome:~$ aws ecr get-login-password | docker login --username AWS --password-stdin 1234567890.dkr.ecr.region.amazonaws.comYou can also use the --token or -t option to specify your token:
admin@myhome:~$ docker login --token usertokenwithrandomcharactersOnce you are logged in, you will be able to push and pull images from the registry.
docker pull
Section titled “docker pull”To pull a Docker image, you can use the docker pull command followed by the image name and a tag. By default, pull will pull a tag latest (latest is the name of the tag, or the version of the image).
For example, use the following to pull the latest version of the alpine image from Docker Hub:
admin@myhome:~$ docker pull alpineUse the following to pull a specific version of the alpine image, such as version 3.12:
admin@myhome:~$ docker pull alpine:3.12You can also pull an image from a different registry by specifying the registry URL in the image name.
For example, use the following to pull an image from a private registry:
admin@myhome:~$ docker pull myregistry.com/myimage:latestdocker push
Section titled “docker push”After you build a new image, you can push that image to the image registry. By default, push will try to upload it to the Docker Hub registry:
admin@myhome:~$ docker push myimageTo push a specific version of the image, such as version 1.0, you will need to tag the image locally as version 1.0 and then push it to the registry:
admin@myhome:~$ docker tag myimage:latest myimage:1.0admin@myhome:~$ docker push myimage:1.0You can also push an image to a different registry by specifying the registry URL in the image name:
admin@myhome:~$ docker push myregistry.com/myimage:latestYou need to be logged in to the registry to which you are pushing the image using the docker login command before pushing an image.
docker image
Section titled “docker image”This is a command to manage images. The common use cases for docker image are shown in the following examples.
To list available images on your machine, you can use the docker image ls command:
admin@myhome:~$ docker image lsREPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu latest 6b7dfa7e8fdb 7 weeks ago 77.8MBmcr.microsoft.com/mssql/server 2017-latest a03c94c3147d 4 months ago 1.33GBmcr.microsoft.com/azure-functions/python 3.0.15066-python3.9-buildenv b4f18abb38f7 2 years ago 940MBYou can also use the docker images command to do the same action:
admin@myhome:~$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEubuntu latest 6b7dfa7e8fdb 7 weeks ago 77.8MBmcr.microsoft.com/mssql/server 2017-latest a03c94c3147d 4 months ago 1.33GBmcr.microsoft.com/azure-functions/python 3.0.15066-python3.9-buildenv b4f18abb38f7 2 years ago 940MBTo pull an image from the Docker registry, use the following:
admin@myhome:~$ docker image pull ubuntuWhen you specify an image name, you can use either the full repository name (for example, docker.io/library/alpine) or just the image name (for example, alpine), if the image is in the default repository (Docker Hub). See also the docker pull command discussed in an earlier section.
It’s also possible to build an image:
admin@myhome:~$ docker image build -t <image_name> .See also the section on the docker build command for more details on building images.
To create a tag for an image, you should run the following:
admin@myhome:~$ docker image tag <image> <new_image_name>Finally, you can remove an image:
admin@myhome:~$ docker image rm <image>See the section on the docker rmi command, which is an alias of this command.
Another option to remove images is the docker image prune – command. This command will remove all unused images (dangling images).
docker exec
Section titled “docker exec”docker exec allows you to run a command in a running Docker container. The basic syntax is as follows:
docker exec CONTAINER COMMAND ARGUMENTSIn the preceding example, the terms have the following meanings:
CONTAINERis the name or ID of the container to run the command inCOMMANDis the command to run in the containerARGUMENTSrepresents any additional arguments for the command (this is optional)
For example, to run the ls command in the container named my_container, you can use the following command:
admin@myhome:~$ docker exec mycontainer lsdocker logs
Section titled “docker logs”docker logs is used to fetch logs generated by a Docker container:
docker logs CONTAINER_NAME_OR_IDAdditional options you can pass to the command are as follows:
--details, -a: Show extra details provided to logs--follow, -f: Follow log output--since, -t: Only display logs since a certain date (e.g., 2013-01-02T13:23:37)--tail, -t: Number of lines to show from the end of the logs (defaultall)
An example of its use is as follows:
admin@myhome:~$ docker logs CONTAINER_IDdocker rm
Section titled “docker rm”docker rm is used to remove one or more Docker containers:
docker rm CONTAINER_NAME_OR_IDAn example of its use is as follows:
admin@myhome:~$ docker rm CONTAINER_IDTo list all containers, use the docker ps - a command.
docker rmi
Section titled “docker rmi”Images that are pulled or built locally can take up a lot of space on your disk, so it’s useful to check and remove unused ones. docker rmi is used to remove one or more Docker images.
The following is its usage:
docker rmi IMAGEAn example of its use is as follows:
admin@myhome:~$ docker rmi IMAGE_IDdocker network
Section titled “docker network”The docker network command is used to manage Docker networks. Apart from the usual actions (create, delete, and list), it’s possible to attach (and disconnect) a running Docker container to a different network.
It’s also possible to extend Docker with a specialized network plugin of your choice. There are multiple options here, so we will just list some of the network plugins with a short description. Plugins can also be used with more advanced setups, such as Kubernetes clusters:
- Contiv-VPP (https://contivpp.io/) uses the Vector Packet Processing (VPP) technology to provide an efficient, scalable, and programmable networking solution for containers, suitable for use in enterprise and service provider environments, where high-performance and scalable networking are a requirement.
- Weave Net (https://www.weave.works/docs/net/latest/overview/) allows containers to communicate with each other, regardless of which host they are running on. Weave Net creates a virtual network that spans multiple hosts, making it possible to deploy containers in a highly available, redundant, and load-balanced manner.
- Calico (https://www.tigera.io/tigera-products/calico/) is one of the most recognizable plugins out there. It uses a pure IP-based approach to networking, providing simplicity and scalability. Calico allows administrators to define and enforce network policies, such as allowing or denying specific traffic flows based on the source, destination, and port. Calico is designed for large-scale deployments and supports both virtual and physical networks.
The following are common operations when using the docker network command:
- Creating a new network:
admin@myhome:~$ docker network create mynetwork- Inspecting a network:
admin@myhome:~$ docker network inspect mynetwork- Removing a network:
admin@myhome:~$ docker network rm mynetwork- Listing networks:
admin@myhome:~$ docker network ls- Connecting a container to a network:
admin@myhome:~$ docker network connect mynetwork CONTAINER_NAME_OR_ID- Disconnecting a container from a network:
admin@myhome:~$ docker network disconnect mynetwork CONTAINER_NAME_OR_IDdocker volume
Section titled “docker volume”The docker volume command is used to manage volumes in Docker. With this single command, you’re able to list available volumes, clean unused ones, or create one for later use.
Docker supports multiple volume drivers, including the following:
local: The default driver; stores data on the local filesystem using UnionFSawslogs: Makes it possible to store logs generated by your applications in Amazon CloudWatch Logscifs: Allows you to mount an SMB/CIFS (Windows) share as a Docker volumeGlusterFS: Mounts the GlusterFS distributed filesystem as a Docker volumeNFS: Mounts the Network File System (NFS) as a Docker volume
Many more drivers are available. The list of available drivers can be found in the official Docker documentation: https://docs.docker.com/engine/extend/legacy_plugins/.
The following are examples of its use:
- List volumes:
dockervolume ls - Create a volume:
docker volumecreate <volume-name> - Inspect a volume:
docker volumeinspect <volume-name> - Remove a volume:
docker volumerm <volume-name> - Mount a volume to a container, which can be done when starting a new container:
docker volumecreate myvolumedocker run -vmyvolume:/opt/data alpine
In this section, we’ve learned how to interact with all Docker components using a command-line interface. Up to now, we’ve been using publicly available Docker images, but it’s time to learn how to build your own images.
Dockerfile
Section titled “Dockerfile”A Dockerfile is essentially a text file with a predetermined structure that contains a set of instructions for building a Docker image. The instructions in the Dockerfile specify what base image to start with (for example, Ubuntu 20.04), what software to install, and how to configure the image. The purpose of a Dockerfile is to automate the process of building a Docker image so that the image can be easily reproduced and distributed.
The structure of a Dockerfile is a list of commands (one per line) that Docker (containerd to be exact) uses to build an image. Each command creates a new layer in the image in UnionFS, and the resulting image is the union of all the layers. The fewer layers we manage to create, the smaller the resulting image.
The most frequently used commands in a Dockerfile are the following:
FROMCOPYADDEXPOSECMDENTRYPOINTRUNLABELENVARGVOLUMEUSERWORKDIR
You can find a complete list of commands on the official Docker documentation website: https://docs.docker.com/engine/reference/builder/.
Let’s go through the preceding list to understand which command does what and when it’s best to use it.
A Dockerfile starts with a FROM command, which specifies the base image to start with:
FROM ubuntu:20.04You can also name this build using as keyword followed by a custom name:
FROM ubuntu:20.04 as builder1docker build will try to download Docker images from the public Docker Hub registry, but it’s also possible to use other registries out there, or a private one.
COPY and ADD
Section titled “COPY and ADD”The COPY command is used to copy files or directories from the host machine to the container file system. Take the following example:
COPY . /var/www/htmlYou can also use the ADD command to add files or directories to your Docker image. ADD has additional functionality beyond COPY. It can extract a TAR archive file automatically and check for the presence of a URL in the source field, and if it finds one, it will download the file from the URL. Finally, the ADD command has a --chown option to set the ownership of the files in the destination. In general, it is recommended to use COPY in most cases, and only use ADD when the additional functionality it provides is needed.
EXPOSE
Section titled “EXPOSE”The EXPOSE command in a Dockerfile informs Docker that the container listens on the specified network ports at runtime. It does not actually publish the ports. It is used to provide information to the user about which ports are intended to be published by the container.
For example, if a container runs a web server on port 80, you would include the following line in your Dockerfile:
EXPOSE 80You can specify whether the port listens on TCP or UDP – after specifying the port number, add a slash and a TCP or UDP keyword (for example, EXPOSE 80/udp). The default is TCP if you specify only a port number.
The EXPOSE command does not publish the ports. To make ports available, you will need to publish them with the use of the -p or --publish option when running the docker run command:
admin@myhome:~$ docker run -p 8080:80 thedockerimagename:tagThis will map port 8080 on the host machine to port 80 in the container so that any incoming traffic on port 8080 will be forwarded to the web server running in the container on port 80.
Regardless of the EXPOSE command, you can publish different ports when running a container. EXPOSE is used to inform the user about which ports are intended to be published by the container.
ENTRYPOINT and CMD
Section titled “ENTRYPOINT and CMD”Next on our list is the ENTRYPOINT command, which in a Dockerfile specifies the command that should always be run when the container starts. It cannot be overridden by any command-line options passed to the docker run command.
The ENTRYPOINT command is used to configure the container as an executable. It is similar to the CMD command, but it is used to configure the container to run as an executable. It is typically used to specify the command that should be run when the container starts, such as a command-line tool or a script.
For example, if you have a container that runs a web server, you might use the ENTRYPOINT command to specify the command that starts the web server:
ENTRYPOINT ["nginx", "-g", "daemon off;"]If you want to run a container with different arguments, you can use the CMD command to set default arguments that can be overridden when the container is started:
ENTRYPOINT ["/usr/bin/python"]CMD ["main.py","arg1","arg2"]CMD is used to specify the command that should be run when a container is started from the image. Take the following example:
CMD ["nginx", "-g", "daemon off;"]The rule of thumb here is that if you want your application to take custom arguments, you are free to use ENTRYPOINT to launch a process and CMD to pass arguments to it. This way, you can be flexible with what your process will do by passing different options via the command line.
The RUN command in a Dockerfile is used to execute commands inside the container. It creates a new layer in the image each time it is executed.
The RUN command is used to install software packages, create directories, set environment variables, and perform any other actions that are required to set up the environment inside the container.
For example, you can use the RUN command to install a package:
RUN apt-get update && apt-get install -y python3 python3-devYou can use the RUN command to create a directory:
RUN mkdir /var/wwwYou can use the RUN command to set environment variables:
RUN echo "export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64" >> ~/.bashrcIt’s worth noting that the order of the RUN commands in the Dockerfile is important, as each command creates a new layer in the image, and the resulting image is the union of all the layers. So, if you’re expecting some packages to be installed later in the process, you need to do it before using them.
The LABEL command is used to add metadata to the image. It basically adds the key-value pairs of data to the image. Those can be used to store information such as the image’s version, maintainer, and other relevant information you might need in your organization. The following is an example of the command:
LABEL maintainer="Chris Carter <[email protected]>"You can also add multiple labels in one line:
LABEL maintainer="Chris Carter <[email protected]>" version="0.2"The labels added to the image can be viewed using the docker inspect command:
admin@myhome:~$ docker inspect --format='{{json .Config.Labels}}' <image_name_or_ID>The use of LABEL commands to add metadata to the image can help users understand what the image’s purpose is or who they should ask about the details, and help to manage the images.
ENV and ARG
Section titled “ENV and ARG”The ENV command is used to set environment variables in the following format:
ENV <key>=<value>The ARG command, on the other hand, is used to define build-time variables. These variables can be passed to the docker build command using the --build-arg flag and their values can be used in the Dockerfile.
The ARG command is used to define build-time variables similar to the ENV format:
ARG <name>[=<default value>]The ARG command creates a variable that is only accessible during the build process, whereas the ENV command creates an environment variable that is accessible to all processes running inside the container.
In the next chapter, we’ll get into more detail about the build process of the Docker image, where ARG and ENV are used together to persist ENV variables across build stages.
VOLUME
Section titled “VOLUME”Another command is VOLUME. With it, you can configure a container to create a mount point for a volume at a specific location. Volumes are a way to store data outside of the container’s filesystem, which means the data can persist even if the container is deleted or recreated. The following is the command:
VOLUME /opt/postgresql_dataUse the following to specify multiple directories:
VOLUME /opt/postgresql_data /opt/postgresql_xferlogOr, the following is also valid:
VOLUME ["/opt/postgresql_data", "/opt/postgresql_xferlog"]If there is any data in the directory marked as volume, when running a Docker using the docker run command, a new volume will be created with the content of this directory. That way, you can ensure that data created while this Docker container is running won’t be lost when the container gets killed or stopped otherwise. It’s especially important for databases, as we suggested in the preceding example.
The USER command in a Dockerfile is used to set the default user that the container runs as. By default, the container runs as the root user; it is recommended to run the container as a custom user without root capabilities.
The USER command is used to set the user and optionally the group that the container runs as. For example, you can use the USER command to run the container as the webserver user:
USER webserverYou can also specify the user and group:
USER webserver:webserverIt’s also possible to set the user ID and group ID instead of the name:
USER 1001:1001The USER command only sets the default user for the container, but you can override it when running the container:
admin@myhome:~$ docker run --user=root webserver-imageRunning your application as a non-root user is a best practice for security reasons. It limits the potential damage that can be done if an attacker gains access to the container, as the process running with full permissions is also running with the same UID (here: root) on the host you are running the image.
WORKDIR
Section titled “WORKDIR”The WORKDIR command in a Dockerfile is used to set the current working directory for the container. The working directory is the location in the container’s filesystem where all the subsequent RUN, CMD, ENTRYPOINT, COPY, and ADD commands will be executed.
You can use the WORKDIR command to set the working directory to /usr/local/app:
WORKDIR /usr/local/appWhen using WORKDIR, you won’t need to set full paths for the files while using any other commands and you could parameterize your application location (with ARG or ENV).
Now that we’ve familiarized ourselves with Dockerfiles and how to build Docker images, it’s useful to know how to store this new image in some way. Docker image registries are used for that exact purpose. We will look into registries in the next section.
Docker image registries
Section titled “Docker image registries”A Docker image registry hosts Docker images. Docker images are organized by tags that can be accessed and downloaded by users. These images can be used to create and run containers on a host machine. Image repositories can be hosted either locally or on a remote server, such as on Docker Hub, which is a public repository provided by Docker. You can also create your own private image repositories to share and distribute your images within your organization.
When you pull an image from a Docker image repository, the image is composed of multiple layers. Each layer represents an instruction in the Dockerfile that was used to build the image. These layers are stacked on top of each other to create the final image. Each layer is read-only and has a unique ID.
Thanks to UnionFS, the Docker registry shares common layers between multiple images and containers, reducing the amount of disk space required. When a container modifies a file, it creates a new layer on top of the base image, rather than modifying the files in the base image. This allows for easy rollback to previous states of the container and makes the images highly portable.
There are multiple image repositories you could use depending on a cloud solution you’re using (ECR for AWS or Google Container Registry for GCP, for instance) or SaaS solutions (Docker Hub is the most popular – https://hub.docker.com). There are also a number of open source licensed solutions available:
- Harbor: This is available at https://goharbor.io/
- Portus: This is available at http://port.us.org/
- Docker Registry: This is available at https://docs.docker.com/registry/
- Project Quay: This is available at https://quay.io and on GitHub at https://github.com/quay/quay
In this section, we’ve familiarized ourselves with Docker registries to store our Docker images in a remote location. In the next section, we will look more into Docker networking and its extensions.
Docker networking
Section titled “Docker networking”There are four types of Docker networking: none, bridge, host, and overlay.
Bridge is the default network mode in Docker. Containers in the same bridge network can communicate with each other. Shortly, it creates a virtual network, in which containers are assigned IP addresses and can cummunicate using them, while anything outside of that network cannot reach any of those addresses. In the Host network, the container uses the host’s network stack. This means that the container shares your machine’s IP address and network interfaces.
Overlay mode allows you to create a virtual network that spans multiple Docker hosts. Containers in different hosts can communicate with each other as if they are on the same host. It’s useful when running Docker Swarm.
Using the Docker command line, you are able to create a custom network of any of those types.
None network
Section titled “None network”A none network in Docker is a special type of network mode that disables all networking for a container. When a container is run in none network mode, it does not have access to any network resources and cannot communicate with other containers or the host machine.
To run a container in none network mode, you can use the --network none option when running the docker run command.
For example, to start a container running the nginx image in none network mode, you would run the following command:
admin@myhome:~$ docker run --network none -d ubuntu:20The none network is useful for running workloads that aren’t supposed to use any network connections, for example, for processing data in a connected volume.
Bridge mode
Section titled “Bridge mode”When using bridge mode on a container being created, a virtual interface is also created and attached to the virtual network. Each container is then assigned a unique IP address on the virtual network, allowing it to communicate with other containers and the host machine.
The host machine acts as a gateway for the containers, routing traffic between the containers and the outside network. When a container wants to communicate with another container or the host machine, it sends the packet to the virtual network interface. The virtual network interface then routes the packet to the correct destination.
By default, it’s a 172.17.0.0/16 network and it’s connected to a bridge device, docker0, in your machine. Within this network, all traffic between containers and the host machine is allowed.
All containers are attached to the default bridge network if no network was selected using the --network option when executing the docker run command.
You can list all available networks using the following command:
admin@myhome:~$ docker network lsNETWORK ID NAME DRIVER SCOPE6c898bde2c0c bridge bridge local926b731b94c9 host host localb9f266305e10 none null localTo get more information about the network, you can use the following command:
admin@myhome:~$ docker inspect bridge[ { "Name": "bridge", "Id": "6c898bde2c0c660cd96c3017286635c943adcb152c415543373469afa0aff13a", "Created": "2023-01-26T16:51:30.720499274Z", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "172.17.0.0/16", "Gateway": "172.17.0.1" } ] }, "Internal": false, "Attachable": false, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": {}, "Options": { "com.docker.network.bridge.default_bridge": "true", "com.docker.network.bridge.enable_icc": "true", "com.docker.network.bridge.enable_ip_masquerade": "true", "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0", "com.docker.network.bridge.name": "docker0", "com.docker.network.driver.mtu": "1500" }, "Labels": {} }]Let’s move on to HOST mode.
Host mode
Section titled “Host mode”In host networking mode, the container shares the host’s network stack and network interfaces. This means that the container uses your machine’s IP address and network settings, and can directly access the same network resources as the machine it runs on, including other containers.
Containers running in host networking mode can also directly listen on a port of the host machine (bind to it).
One of the main advantages of host networking mode is that it provides better performance as the container doesn’t have to go through an additional network stack.
This mode is less secure than the other networking mode as the container has direct access to the host’s network resources and can listen to connections on the host’s interface.
Overlay
Section titled “Overlay”An overlay network is created by a manager node, which is responsible for maintaining the network configuration and managing the membership of worker nodes. The manager node creates a virtual network switch and assigns IP addresses to each container on the network.
Each worker node runs Docker Engine and a container network driver, which is responsible for connecting the containers on that host to the virtual network switch. The container network driver also ensures that packets are properly encapsulated and routed to the correct destination.
When a container on one host wants to communicate with a container on another host, it sends the packet to the virtual network switch. The switch then routes the packet to the correct host, where the container network driver decapsulates the packet and delivers it to the destination container.
The overlay network uses the Virtual eXtensible Local Area Network (VXLAN) protocol to encapsulate IP packets and make it possible to create a Layer 2 network between multiple hosts.
Summary
Section titled “Summary”In this chapter, we have introduced one of the major building blocks of modern DevOps-led infrastructure, that is, containers. We described the most prominent container technology – Docker. We have also introduced the basics of running Docker containers and building your own. In the next chapter, we are going to build on this knowledge and introduce more advanced Docker topics.