Skip to content
ImagineWorld

Containerizing Applications with Docker

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-13-containerizing-applications-with-docker
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num13
chapter_titleContainerizing Applications with Docker
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 13 — Containerizing Applications with Docker

Section titled “Chapter 13 — Containerizing Applications with Docker”

Over the last decade, Docker containerization has become a kind of default packaging format for web applications and modern microservices. In a container, your program sits in a very lightweight, isolated shell of Linux filesystem, process, user, and network abstractions, safely separate from the host environment. Container images also happen to be incredibly portable – they’re easy to shuffle around from a developer’s laptop to a testing or staging environment to a production server. This solves many of the problems that have plagued software and infrastructure over the last several decades.

In some sense, containers are quite similar to the Linux packages you’ve learned how to install from repositories. A container image is, roughly, a compressed archive (such as, a .tar.gz file) of your application, along with all the configuration files and dependencies the application needs. That little package – an image – is executable by Docker. The revolutionary thing about such a container is that it neatly holds everything together in a single artifact and can run on any Linux system that has a container runtime (like Docker) installed.

This chapter could easily be a book on its own – Docker and Linux containers in general are fairly large subjects. However, like with everything else in this book, we’re focusing on only the basic theory and practical skills that are necessary for you to be comfortable interacting with Docker-based infrastructure in your applications.

In this chapter, you’ll learn about the following:

  • The application development and operational problems that containers solve
  • What containers are, and how they’re similar to Linux packages
  • The difference between Docker images and Docker containers
  • All the practical basics for using Docker in your development workflow
  • How to build your own container images with Dockerfiles (you’ll containerize a real Python web application)
  • Some more advanced topics like how virtual machines and containers are different, and how Linux creates container abstraction via namespacing
  • Some hard-earned container tips, tricks, and best practices

Let’s jump in.

Docker became standard tooling to package up software when the goal is to include a system that is known to be a working setup. A Docker container typically contains both the software you want to run as well as a whole, though frequently trimmed down, Linux system as its execution environment. This execution environment provides libraries and tools, as well as some other things, like basic system configuration, so that it can function as a standalone entity, independent of the system running the container. The primary goal is to make sure that the application can successfully be run on the developer’s machine, production and test environments, and elsewhere, without having to take care of details, such as the operating system versions, installed libraries.

It is important to keep in mind that the operating system and libraries don’t disappear. Bugs in libraries may still exist and any packaged dependencies should be updated for security and other reasons. However, the consumers of the packaged software, be it end users or your system operators, as well as any orchestration software, are now provided with a common package and don’t need to take care about system dependencies. While the details of how the software is run and configured still depend on the software, the way it is executed (in a container) is somewhat standardized.

In summary, that means that any specific setup of the environment, such as installing dependencies, is now described as part of the Dockerfile, and once a working container image is created, short of specific configuration, the container is expected to run on any system capable of running Docker, or more broadly, OCI images.

OCI (short for Open Container Initiative) provides standards to specify things like image format and the execution of Linux containers. Sometimes it used synonymously with Docker in the sense that a developer might use Docker to create the image, but the execution on an orchestrator might not use Docker at all.

There’s no better way to get started than to install Docker on your machine and start trying some commands, so let’s do that.

First, download and install Docker Desktop. You can find instructions for this at https://docs.docker.com/get-docker/.

There is also an excellent official tutorial for getting started at https://docs.docker.com/get-started/, but we recommend that you wait to read that until after you’ve gone through this chapter. We’re going to cover some of the basics, but with less focus on specific command-line flags, and more focus on how you’ll use these commands and workflows as an application developer.

Now that you’ve got Docker installed, let’s jump into actually starting our first container!

A Docker image is the “package” from our metaphor – it’s a static artifact that is saved, stored, and moved around. It becomes a container when it’s executed on a machine. This is important because you’ll sometimes hear these terms used incorrectly: Docker images are the immutable base from which a container – a running, namespaced process – is launched. Images are the pre-built template from which live containers are generated at runtime.

Images are designed to be immutable: if you download an nginx web server image and run it, any changes you make to the resulting container don’t affect the underlying image at all. This is the part that trips up most developers who are used to long-running virtual machines that are provisioned once and then started and stopped many times, preserving their internal state the whole time.

Docker containers are different. Ideally, they are designed to be ephemeral and stateless, while the images they’re spawned from act as a long-lived blueprint that can be used to spawn an infinite number of containers across many different execution environments.

What follows is an example of a basic Docker workflow that’s designed to get you acquainted with the most important Docker commands. Don’t worry about memorizing the commands; we’ll cover them in depth later in this chapter. For now, we’ll just explain what’s happening at each step, so you can get used to what you’ll see on the screen at your next microservices gig.

First, let’s start the nginx container (docker run) and interactively (-it) run the Bash shell (/bin/bash) inside of it:

→ ~ docker run -it nginx /bin/bash

This gets us a shell prompt for the unique container that was started from the nginx image. The container’s Bash shell is now connected to our terminal:

root@e96107c9a58e:/#

Let’s write a file called test.txt and verify that it exists:

root@e96107c9a58e:/# echo "I am immutable" >> test.txt
root@e96107c9a58e:/# cat test.txt
I am immutable

We can exit the shell with the usual command, ctrl-d:

root@e96107c9a58e:/#
exit

The container exits and we’re now back in our regular shell. Here’s where it gets confusing for most first-time Docker users: let’s re-run the first command to start a container from the nginx Docker image again, and check on our file:

→ ~ docker run -it nginx /bin/bash
root@c3b4d95ab9e6:/# cat test.txt
cat: test.txt: No such file or directory

FILE A BUG REPORT! DOCKER IS BROKEN!

Actually, it’s not. This is not the same container as the one you wrote the test.txt file in. If you were looking closely, you may have noticed that the hostname in the shell prompt was different on the second container. That’s because each docker run command launches a new container from the specified image. Containers are designed to run, exit, and disappear forever.

The original container is actually still around:

→ ~ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c3b4d95ab9e6 nginx "/docker-entrypoint.…" 14 minutes ago Exited (1) 6 minutes ago agitated_hofstadter
e96107c9a58e nginx "/docker-entrypoint.…" 14 minutes ago Exited (0) 14 minutes ago nervous_gould

To get rid of them, you can use docker rm with the ID of the container you want to delete:

→ ~ docker rm c3b4d95ab9e6
c3b4d95ab9e6

It is possible to start a stopped container with docker start:

→ ~ docker start e96107c9a58e
e96107c9a58e

At which point, you would see the container running in your Docker process list:

→ ~ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e96107c9a58e nginx "/docker-entrypoint.…" 18 minutes ago Up 1 second 80/tcp nervous_gould

Then you could use docker exec to execute a command inside that container, again starting and attaching to the Bash shell program with –it. From there, you can view the filesystem state (test.txt) that we modified:

→ ~ docker exec -it e96107c9a58e /bin/bash
root@e96107c9a58e:/# cat test.txt
I am immutable

However, keeping containers around for a long time – modifying their state and stopping and restarting them instead of always starting new containers from an image – is discouraged and leads back to many of the same bugs that Docker helped solve.

Let’s avoid all of those mistakes and delete this running container forever by force-removing it:

→ ~ docker rm -f e96107c9a58e
e96107c9a58e

You could have also run docker stop followed by docker rm, but force-removing with docker rm -f will stop and remove a running container in one fell swoop.

You can see how Docker encourages immutable containers to keep the state from drifting away from the image, which is the “source of truth” for your application’s initial environment. If you want to make changes to an image, you can’t do so directly – images are immutable.

Changes should be explicit and intentional, which is important for creating and running reliable software. How do we do this? We start with the original image, make our changes in a controlled and reproducible way (not “SSH to the server and try running these commands”), and then save them by creating a new image. Enter the mighty Dockerfile.

If you’re ever tasked with building a new Docker image, or modifying an existing one – perhaps for a web application that you’re developing – you’ll be making heavy use of Dockerfiles (see the official Dockerfile documentation at https://docs.docker.com/engine/reference/builder/).

A large percentage of new software will already have an official (or at least open-source, third-party) Dockerfile available. Even if you need to do some customizing before you use these, a good place to look for examples is the documentation for the software or framework you use. These examples don’t tend to break as easily as your own custom Dockerfile when major upgrades are released for the packaged software.

Also, some frameworks or development environments, for example, Spring Boot (Java), can generate Docker images as part of the build process.

So, even though there’s a chance you’ll never have to touch a Dockerfile yourself, it’s unlikely, and you should have a basic idea of how they work.

Let’s look at a very simple Dockerfile, from the open-source HTTP echo server project (https://github.com/hashicorp/http-echo). This creates a Docker image that packages a Go binary that acts as a simple web server:

FROM alpine
ADD "https://curl.haxx.se/ca/cacert.pem" "/etc/ssl/certs/ca-certificates.crt"
ADD "./pkg/linux_amd64/http-echo" "/"
RUN apk add curl
ENTRYPOINT ["/http-echo"]

Basically, this creates a new container image by:

  1. Using the alpine Linux image as a base to build on.
  2. Downloading some certificates and adding them to an image layer (essentially adding something to the resulting container’s filesystem).
  3. Copying the http-echo binary from the build directory into the container image.
  4. Running an alpine package installation command to install the curl program.
  5. Defining the executable or command that is run when a container started from this image is launched.

Each of these steps is invoked by a (capitalized) Instruction that the Dockerfile parser knows how to execute. This specific Dockerfile only uses a subset of the instructions available to you in a Dockerfile (FROM, ADD, RUN, and ENTRYPOINT).

Here’s the full complement of instructions available to you when you’re creating new Docker images via a Dockerfile:

  • ARG: Declares a build-time argument; basically, a variable to be used later in the build.
  • ENV: Environment vars to set during the build, which will persist in your running container environment (not just during the build!). Takes a key=value format.
  • FROM: Base image.
  • CMD: This provides a default command (or default ENTRYPOINT args) for the container to run when it’s started. It can be overridden, but you should have one in your Dockerfile. Only one per Dockerfile is allowed – if there’s more than one CMD, only the last one will count.
  • ADD: A flexible instruction that copies files and directories, adding them to the image’s filesystem. This can also be used to copy files from outside the image or from remote URLs (via HTTP), and to do complex things like expansion, decompression, unarchiving, and more. You saw it as a stand-in for the curl command in the sample Dockerfile above, to download a CA certificate file.
  • COPY: Just copies files and directories – less complicated, magical, and powerful than ADD.
  • LABEL: Adds image metadata, in a key=value format.
  • EXPOSE: Informs consumers of this image about which network protocols and ports this container will be listening on.
  • ENTRYPOINT: Tells the container what command to run when it starts. Use the exec form (ENTRYPOINT ["executable", "param1", "param2"]) to make sure your container can receive and respond to signals from outside the container process.
  • RUN command arg1 arg2: Run command with arguments arg1 and arg2 in the image’s shell:
    • RUN ["command", "arg1", "arg2, "argN"]: Same as above, but useful to avoid shell string munging.
      • Each RUN instruction executes in a new image layer (we’re not diving into layers here but this can be helpful to know).
      • RUN --mount can be used to temporarily mount filesystems into the container during the build, without copying the files themselves into an image layer.
      • RUN --network and RUN --security also exist for managing network context and privileged containers, respectively.
  • WORKDIR: Sets the working directory for instructions that follow in the Dockerfile. Equivalent to cd in Unix-like operating systems.
  • SHELL: Override the default shell used to interpret commands during the Docker build. Commands must use the exec form.
  • STOPSIGNAL: Set the system call signal that this container should interpret as the signal to exit. By default, this is SIGTERM, like any other Linux process.
  • VOLUME: Define volumes that will be mounted in from the host.
  • USER: Change (container) user to use for build commands, from this point forward (can be used multiple times to switch users during a build).
  • ONBUILD: Define an instruction that’s triggered when this image is used as the base for another build.
  • HEALTHCHECK: Some health-checking functionality, which you likely won’t use because your container scheduler has its own health-checking functionality.

We’ll jump into a practical, end-to-end example of how to tie all of this together with a small project, but first let’s revisit the commands we just used in a bit more depth.

Now let’s dive deeper into some of the more complicated, but important, commands and command invocations that you may run into when working with Docker.

Let’s look at a more complex invocation of the docker run command we used earlier:

docker run --rm --name mywebcontainer -p 80:80 -v /tmp:/usr/share/nginx/html:ro -d nginx
  • --rm: Clean up (remove) this container when it exits.
  • --name mywebcontainer: Give this container a friendly name – mywebcontainer.
  • -p 80:80: Map port 80 of the host to port 80 in the container. The left port number is on the “outside” (the environment running the container), and the right port number represents the “inside” (container) port. For example, -p 4000:80 will map the container’s port 80 to localhost:4000.
  • -v /tmp:/usr/share/nginx/html:ro: Mount a volume – the host environment’s /tmp directory will be mounted into the container at /usr/share/nginx/html; :ro ensures that this will be a read-only mount (mounted files can’t be modified from inside the container).
  • -d: Run the container in detached mode (in the background).
  • nginx: The image to launch this container from.

If you want to see some HTML at http://localhost:80, you can add an index.html file to your /tmp directory:

cat <<EOF > /tmp/index.html
<!doctype html>
<h1>Hello World</h1>
<p>This is my container</p>
</html>
EOF

Because our /tmp directory is mapped to the container’s /usr/share/nginx/html directory (where nginx will look for HTML files), nginx will immediately recognize and begin serving this file.

Volumes are the mechanism by which stateful applications can still be run using stateless containers.

To see which images you’ve downloaded locally, you can run docker images (or docker image list, if you prefer).

The list may be long if you’ve been building and using lots of Docker images!

$ docker image list
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 51086ed63d8c 10 days ago 142MB
vault latest 22fdc6314051 2 months ago 207MB
golang 1.19-alpine d0f5238dcb8b 2 months ago 352MB

docker ps is a bit like the ps command in Linux. It lets you see which containers are running on your host, along with some context like their ID, which command they are running, their creation time and uptime, port mapping, and more.

Running the command

$ docker ps

will produce output like this:

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2aca849eef73 nginx "/docker-entrypoint.…" About a minute ago Up About a minute 0.0.0.0:80->80/tcp mywebcontainer

During the development of a container image, it’s common to jump into a container and run commands. To start an interactive shell in a running container, use docker exec:

docker exec -it mywebcontainer /bin/bash

In the case of our previously started nginx container, this will spawn a Bash shell inside the container environment. Any state changes you make (file creation, kernel settings, and so on) will be lost when the container is stopped – the next docker run will simply spool up a new container from the same base image state.

To stop a container, run docker stop $CONTAINERNAME – you can also use the container ID if it doesn’t have a friendly name:

docker stop mywebcontainer

If the container was started with the --rm option, as our nginx container was, the container will be deleted and its state (if that state diverged from the base image) will be lost.

If the container was not started with --rm, its state remains on your filesystem and you can start the container again with docker start $CONTAINERNAME. Its state will be preserved.

Docker project: Python/Flask application container

Section titled “Docker project: Python/Flask application container”

We’re going to containerize a small Python web service that uses the Flask web framework. This is an extremely common pattern, and Python lends itself well to containerization because packaging and dependency management are famously messy in a lot of Python projects. You’ll create all the files yourself – try to use a command-line text editor for practice!

First, create a new directory and enter it:

mkdir dockerpy && cd dockerpy

Create the tiny Python web application. I’m using vim in this example, but use whichever editor you like:

vim echo_server.py

Paste the following text inside:

from flask import Flask, request
import os
app = Flask(__name__)
@app.route('/')
def echo():
return {
"method": request.method,
"headers": dict(request.headers),
"args": request.args
}
@app.route('/health')
def health():
return {"status": "healthy"}
if __name__ == "__main__":
env_port = os.environ.get("PORT", 8080)
app.run(host='0.0.0.0', port=env_port)

That’s the whole web application – it simply reads some of the information from an incoming request and uses that to push a response back to the client.

Save and exit the file (esc, :x).

Create a file named requirements.txt containing just the following line:

Flask>=3.0.0

Next, create your Dockerfile:

vim Dockerfile

Enter the following text:

# Use an official Python base image
FROM python:3.12-slim
# Set the working directory inside the container
WORKDIR /app
# Copy our list of dependencies into the container
COPY requirements.txt .
# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the script into the container
COPY echo_server.py .
# Set a healthcheck to kill the container if it's not listening on the internal port
HEALTHCHECK --interval=30s --timeout=5s \
CMD curl --fail http://localhost:8080/health || exit 1
# Expose port for the application
EXPOSE 8080
ENV PORT=8080
CMD ["python", "echo_server.py"]

That’s all you need for now. Your dockerpy directory should now contain three files:

  • Dockerfile
  • echo_server.py
  • requirements.txt

Build a new Docker image with the docker build command. The -t is for “tagging” the container with a name:

docker build -t dockerpy .

Notice the . character at the end, which is telling Docker to use the current directory as its build context.

You’ve already used the docker run command earlier in this chapter. Use it to launch a container from your newly built image:

docker run --rm -d -p 8080:8080 --name my-dockerpy dockerpy
(the command will print out the ID of your new container)

There are a few new arguments here:

  • --rm tells Docker to delete the container when it exits. This prevents old containers from hanging around on your filesystem, as you saw in the first examples in this chapter.
  • -d tells Docker to daemonize the container. This keeps it from attaching to your terminal in the foreground.
  • -p sets up a port mapping: the left side of the colon is the container port, while the right side is the host port that it’ll be mapped to. If the container application were running on port 1234 and you wanted it to map to host port 80, this would read –p 1234:80.
  • --name tags your container with a name so you can find it easily in the output of docker ps.

Now you’ve got your containerized application running, and can access it in a browser or on the command line. Let’s use the curl command to connect to send a request to the web service:

curl localhost:8080
{"args":{},"headers":{"Accept":"*/*","Host":"localhost:8080","User-Agent":"curl/8.1.2"},"method":"GET"}

For those who have suffered through impossible-to-recreate dependency nightmares (Python, Ruby, and others are famous for this), this should be a revelation. All of the complexity that you used to have to drag around with your application – from local dev environments to CI and testing, to staging, and finally to production – is now condensed into a single artifact that’s guaranteed to contain the same stuff no matter where you run it.

One command we haven’t used before is docker exec, which lets you execute a command inside a running container. This is useful if, for some reason, you absolutely have to inspect or modify a running container:

docker exec -it my-dockerpy /bin/sh

This launches and attaches to /bin/sh in the container (most production containers will only have a minimal shell at /bin/sh, and won’t ship with something as full-featured as Bash).

Let’s stop the server with the last command we’ll cover here, which is docker kill:

docker kill my-dockerpy

This sends a SIGKILL (Signal 9) as opposed to a SIGTERM (Signal 15) to the process and stops it immediately without giving it the chance to shut down gracefully.

You’ve now gotten a taste of the workflow that you’ll use to create and work with Docker images. However, it pays to know a bit about the underlying differences between containers and virtual machines. This knowledge can make a difference when you’re troubleshooting operational issues, and it’s also a common interview question to gauge how well you understand the principles underlying containerization.

Virtual Machines (VMs) allow you to run complete operating systems like Linux, Windows, or DragonFly BSD on top of another host operating system. VMs run independently of the host system. In fact, running Docker on macOS will transparently use a VM to provide the Linux OS that’s needed for Docker.

As a result, a virtual machine runs a full operating system like Linux, which in turn uses an init system like systemd. Because of this, you manage services and processes exactly as if your VM were a physical machine. In terms of day-to-day use, everything that applies to a physical machine also applies to virtual machines. However, this is not how containers are typically used.

Docker containers usually contain single applications; in fact, they frequently contain only a single process. If there happen to be multiple processes inside a container, this is typically because of a multi-process application that has spawned child processes (web servers or command runners usually do this). Since the widely agreed-upon best practice is for a container to run only a single process, and to exit as soon as that process exits, any kind of internal process supervision and management would be wasted here.

Instead, you’ll find that the jobs typically done by an operating system’s init system have moved outside the container runtime environment, to the external systems managing the containers, such as Kubernetes, Nomad, and others.

In this new model, containers are what operating system processes used to be, and container orchestrators play assorted OS and scheduler roles.

In a Docker container, PID1, which is the init system on a full Linux operating system, is whatever your CMD or ENTRYPOINT is. Usually, that’s the main process of the software you’re running. Typically, a container is expected to run a single process. While there are scenarios where people intentionally run their containers in a different way, running a single process and having the container halt when the process halts is the expected behavior. Especially when simply containerizing a service to be run in production, one should make sure to follow this approach. There are exceptions to this rule, especially when running software that predates the popularization of Docker containers, but in these cases, you’ll likely be aware and often base off containers made for this purpose.

We’ve been working quite a bit with the nginx image in this chapter. But where exactly is this image coming from? By default, Docker attempts to download images from Docker Hub (https://hub.docker.com/), which is a central repository of public Docker images. Docker Hub works like a Linux package repository, which contains uploaded Docker images ready for you to use. Most popular server software can be found there and can be downloaded and used as easily as you just saw with nginx.

Not all applications are public, however, and it’s normal to use private repositories to store Docker images. There is an ever-changing list of Docker image repository providers, so we won’t list them here, but it’s enough to understand that they all work the same way as Docker Hub.

As you start building your own containers, you can avoid many problems by keeping in mind the best practices discussed in Docker’s official documentation here: https://docs.docker.com/get-started/09_image_best/.

That said, we’ve compiled a small list of the most egregious containerization mistakes we’ve noticed, and how to avoid them. This section is the result of many sleepless nights, outages, and learning things the hard way.

Start with minimal images, like Scratch or Alpine. To deploy most applications, it’s a good idea to try to stay away from big images and distributions like Ubuntu. When build dependencies are required, removing these, or using intermediate build containers when building larger/multi-container projects, is recommended.

Small, minimal images don’t just mean faster download speeds and less resource usage, but also make it a lot easier for you to manage. If an image doesn’t include software and libraries you don’t need, that’s less for you to keep updated, less surface area for criminals to attack, and fewer noisy warnings from container security scanners.

Be aware of which C Standard Library (also known as libc) you’re using. Many Linux distributions use glibc; some, like Alpine Linux, use musl or others. The libraries and any resulting binaries might not be compatible across those. For example, on Alpine, you may need to compile less popular tools yourself. If your projects depend on certain libraries being available via packages on your base image, you might run into incompatibilities. Of course, upgrading, downgrading, or switching base images completely might cause similar issues.

However, because Alpine and musl have been steadily gaining adoption, these sorts of issues are becoming less likely (and, at the very least, more googlable!). If you don’t depend on any C libraries, this usually won’t be an issue. Also, statically compiling your code can make you more independent of the underlying system and therefore the base image.

Production is not your laptop: outside dependencies

Section titled “Production is not your laptop: outside dependencies”

Don’t depend on local mounts or other local containers. The environment for a deployed container will likely be very different from your laptop. Just because you’ve got a database container next to your web app container on your laptop, doesn’t mean these containers will be scheduled on the same machines in production.

The same thing goes for data volumes – these outside-your-container touchpoints are where you’ll have to do some planning with your Ops/DevOps co-workers. You’ll likely be hooking into service discovery, health checking, and shared volumes via a scheduler or other DevOps tooling construct.

If you’re wondering how some of this container magic works underneath, or just worried that you’ll have to troubleshoot a container environment under pressure one day, it’s useful to familiarize yourself with the concept of namespacing. You can skip this section if you’re not interested in how the container abstraction is built on Linux.

Namespacing is an overloaded term, used to mean different things in different technological niches. In the context of Linux containers, the idea of namespacing is best explained via chroot (change root). chroot is an old utility for Unix and Unix-like operating systems that allows a user to change the root (the / path) of the filesystem.

The usage of this tool is really quite simple: chroot /some/path will set whatever is in /some/path to be the new /. In addition to allowing OS installers to change into the system that is currently being installed to run commands, it also allows for basic namespacing. In fact, various software and the configuration of various Linux distributions have been making use of this to enhance security, because using chroot essentially excludes parts of the filesystem from the currently readable scope – it makes anything outside the new root inaccessible. So, if an attacker uses an exploit that allows for remote code execution on a web server running inside a chroot environment, the system and any files outside this directory will remain unaffected.

The technical primitives used to implement containers on Linux and other operating systems have changed significantly over the last decade, and will likely continue to change. Thankfully, the low-level implementation is not critically important for you as a software engineer who is mainly a consumer of containerization, as opposed to an operator or implementer of this technology.

The “container” abstraction relies on underlying technologies like:

  • Filesystem namespacing (for example, with chroot).
  • User and process namespacing, making processes outside the container invisible from within the container. In other words, root and PID 5 in the container would respectively map to an unprivileged user and another process ID outside of the container namespace.
  • Resource grouping and accounting technologies such as cgroups.
  • Network virtualization/namespacing, so a container can’t access a network interface directly, but also so that port number overlaps can be handled. For example, you can run two different containers that expose port 8080; there won’t be an error about the port being already in use, because the containers’ networking stacks are independent of each other.

Although this is not a book for system administrators or site reliability engineers, you should know the basic context in which containers are generally run. The main idea is that containers are largely stateless “functions” that process inputs (web requests or HTTP messages from other services) and produce outputs (web responses, side effects, and logs streamed to STDOUT). In a well-run operations environment, containers can be thought of as an analog to Linux processes, or to functions in programming.

Containers are usually “scheduled” onto hosts by a third-party tooling layer such as Kubernetes, Nomad, and others. If containers are like processes, then these fill the role of the operating system scheduler (the whole thing is a distributed system instead of a single host).

Container output is usually captured by the same tooling and redirected to logging solutions such as Logstash, Graylog, and Datadog. Metrics from all running containers may be extracted and fed into tools like Prometheus for analysis and troubleshooting.

In this chapter, you got a whirlwind tour of the most important things you need to know about working with Docker, and containers in general. Although individual technologies may change – which container scheduler is in vogue, or how log streaming is best handled – we’ve tried to stay focused on the core theory and skills that every modern software developer should have.

We hope that you take away a few main ideas from this chapter. First, we hope you have an intuitive grasp of the problems that containerization solves for people, mainly by controlling complexity and packaging dependencies into a single artifact.

It’s also important to remember the difference between images and containers, and to get some practice building your own Dockerfiles from scratch, using the official documentation.

We hope that visiting a few more advanced topics, like how virtual machines and containers are different and how namespacing works, comes in handy during troubleshooting or a job interview. The best practices we discussed will come in handy there, too.

Finally, to cement your learning, we recommend that you practice these skills by containerizing one of your own applications. You’ll learn a lot and it’ll be much easier to start while all of the information from this chapter is still fresh in your mind.