Linux Containers Explained: namespaces, cgroups, OCI images, runtimes, engines with and without a daemon

Linux Containers Explained: OCI, Runtimes and Engines

Share this post on:

More and more embedded products run their applications in containers, so that the teams that write the applications can ship them without rebuilding the whole system. Choosing and configuring an engine for a device is easier once the pieces underneath are clear, from what the kernel provides to what an image and a runtime are and how Docker, containerd and Podman differ.

The outputs below come from three arm64 hosts built with Yocto and run in QEMU, one per engine, all running the same small application image. Our article on containers with Yocto shows how those hosts and the image are built, installed and updated.

Contents
  1. Benefits and Costs on a Device
  2. Containers and Virtual Machines
  3. Kernel Features Behind Containers
  4. The OCI Image
  5. The OCI Runtime
  6. The Container Engine
  7. Engines with a Daemon: Docker and containerd
  8. Podman, an Engine without a Daemon
  9. Kubernetes, and System Containers
  10. PID 1 and Signals
  11. Users in Rootful and Rootless Containers
  12. Summing Up

Benefits and Costs on a Device

On a server, containers mostly pack services densely. On an embedded device, other properties count. An application in a container carries its own libraries, so it does not break when the base system updates one, and the base system does not break when an application needs another version. Each application can be updated alone, from a registry, while the base system follows its own release cycle. The image that passed the tests in CI is the one that runs on the device, and a cgroup keeps a misbehaving application from starving the others of memory or CPU.

Containers also have costs. The engine adds tens of megabytes to the root file system and a service that must start before the applications, each image needs storage, and the engine becomes part of the attack surface of the device. A device that runs one application built with the system gains little from containers.

Containers and Virtual Machines

A virtual machine runs a complete guest system, with its own kernel, on top of a hypervisor that emulates or partitions the hardware. A container has no kernel of its own. Its processes run directly on the kernel of the host, which isolates them from the rest of the system. A container therefore starts as fast as a process, adds no guest kernel to the memory footprint, and must be built for the architecture of the host. It also shares the fate of the host kernel, since a kernel vulnerability concerns every container of the device.

Kernel Features Behind Containers

Isolation comes from several kernel features combined. Namespaces give a process its own view of one kind of resource. The mount namespace gives it its own mount table, the PID namespace its own process numbers, the network namespace its own interfaces and routes, the UTS namespace its own host name, the IPC namespace its own System V IPC objects, the user namespace its own user IDs and the cgroup namespace its own view of the control groups. The kernel shows them as links in /proc/<pid>/ns. readlink compares PID 1 of the host with the application running in a Docker container:

root@qemuarm64:~# P=$(pidof frame-counter)
root@qemuarm64:~# for n in mnt pid net uts ipc user cgroup; do echo $n $(readlink /proc/1/ns/$n) $(readlink /proc/$P/ns/$n); done
mnt mnt:[4026531832] mnt:[4026532236]
pid pid:[4026531836] pid:[4026532239]
net net:[4026531833] net:[4026532241]
uts uts:[4026531838] uts:[4026532237]
ipc ipc:[4026531839] ipc:[4026532238]
user user:[4026531837] user:[4026531837]
cgroup cgroup:[4026531835] cgroup:[4026532240]
root@qemuarm64:~# cat /proc/$P/cgroup
0::/system.slice/docker-903edc2cd7a71c0402911a27ad98227a376c7647b7fc895c04cbc1127a7a501c.scope

The container has six namespaces of its own and shares one with the host, the user namespace, which the last section comes back to. Control groups, cgroups, limit and account the CPU, memory, I/O and number of processes of a group of processes. Docker put the application in a cgroup of its own, docker-<id>.scope, under the system.slice of systemd.

The root file system of the container is an overlay file system that stacks the read-only layers of the image under a writable layer, so that several containers share the files of the same image. A pair of virtual Ethernet interfaces, veth, links the network namespace of the container to a bridge of the host.

A container process with its namespaces, cgroup and veth interface, and its overlayfs root file system
Figure 1. The kernel features of a container, the same whatever the engine, with its overlayfs root file system mounted as /.

An engine only automates calls to these features, and a shell can make some of them by hand. unshare of util-linux starts a command in new namespaces, and a cgroup is a directory of /sys/fs/cgroup:

root@qemuarm64:~# unshare --pid --fork --mount-proc --uts --net --ipc sh -c "hostname box; hostname; ip -o link; ps"
box
1: lo: <LOOPBACK> mtu 65536 qdisc noop qlen 1000\    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: sit0@NONE: <NOARP> mtu 1480 qdisc noop qlen 1000\    link/sit 0.0.0.0 brd 0.0.0.0
PID   USER     TIME  COMMAND
    1 root      0:00 ps
root@qemuarm64:~# mkdir /sys/fs/cgroup/box
root@qemuarm64:~# echo 50M > /sys/fs/cgroup/box/memory.max
root@qemuarm64:~# cat /sys/fs/cgroup/box/memory.max
52428800
root@qemuarm64:~# echo $$ > /sys/fs/cgroup/box/cgroup.procs
root@qemuarm64:~# cat /proc/self/cgroup
0::/box

In its own namespaces, the shell has its own host name, sees only the loopback interface and a tunnel interface the kernel creates in every network namespace, and its last command is process 1. The shell that joined box and every process it starts can use 50 MB of memory at most. A container is the same thing plus a root file system made from an image, a network link to the outside, seccomp filters, capabilities and devices restricted, and cleanup when it ends, which is what the engine and the runtime handle.

The OCI Image

A container image follows the image format of the Open Container Initiative, OCI. It is a stack of file system layers, each a tar archive, and a JSON configuration. The configuration of the image used in this article, read with skopeo:

$ skopeo inspect --config oci:frame-counter-image-latest-oci:latest
[...]
    "User": "1000",
    "ExposedPorts": {
      "8080/tcp": {}
    },
    "Env": [
      "FRAME_INTERVAL=5"
    ],
    "Entrypoint": [
      "/usr/bin/frame-counter"
    ],
    "Cmd": [
      "camera0"
    ],
    "WorkingDir": "/",
[...]

Entrypoint is the program that always runs, and Cmd its default arguments, which the user replaces by passing others. Env, User, WorkingDir and ExposedPorts describe the environment the program expects. Every engine reads this format, so the same image runs on the three hosts. The OCI also defines the runtime format described in the next section and the distribution API that registries implement. Docker images use an older format of Docker, almost identical, and Docker, containerd and Podman read both.

The OCI Runtime

The runtime is the program that creates a container, and nothing else. It receives a bundle, a root file system and a config.json in the OCI runtime format, creates the namespaces and the cgroup, mounts the file systems, starts the process and exits. It knows nothing about images, registries or networks. runc, written in Go, is the reference runtime. crun implements the same format in C, with a smaller binary and a faster start, which matters on a small device. The two are interchangeable, and on the containerd host of this article runc is only a link to crun:

root@qemuarm64:~# ls -l /usr/bin/runc /usr/bin/crun
-rwxr-xr-x    1 root     root        667680 Apr  5  2011 /usr/bin/crun
lrwxrwxrwx    1 root     root             4 Apr  5  2011 /usr/bin/runc -> crun

Anything that expects runc, here the containerd shim, runs crun without knowing it.

The size difference is large on a device. On the hosts of this article, runc is 12.4 MB and crun 0.67 MB. Hardened runtimes add isolation at a cost. Kata Containers, which meta-virtualization packages as kata-runtime and kata-agent, runs each container in a lightweight virtual machine with its own kernel, and gVisor, which the layer does not package, intercepts the system calls of the container in a kernel written in user space. Both need far more resources than runc or crun and are rare on embedded devices.

The Container Engine

The engine manages everything around the runtime, over the whole life of a container. It pulls an image from a registry and stores its layers. To create a container, it unpacks the layers into an overlay root file system, writes the config.json from the image configuration and the options of the user, and prepares the network namespace. It then calls the runtime to start the container, and later stops it, collects its output and exit status, and removes it. Docker, containerd and Podman all do this, but they are organized differently.

Each engine relies on helpers for parts of that work. Networking goes through CNI plugins for containerd, through netavark with aardvark-dns for name resolution in Podman, and through the network code of dockerd for Docker. Rootless containers use pasta or slirp4netns, network stacks in user space. Podman watches each container with conmon, and small init programs, tini or catatonit, can run as process 1 of a container. The binaries alone show the weight of each engine on the hosts of this article:

dockerd                    88 MB
containerd                 54 MB
containerd-shim-runc-v2     8.8 MB
docker (client)            30 MB
nerdctl (client)           32 MB
podman                     47 MB
conmon                      0.2 MB

A Docker host carries dockerd, containerd and the docker client, a containerd host only containerd and a client, and a Podman host a single program and a small monitor.

Docker, containerd and Podman stacks from client to OCI runtime; daemons dockerd and containerd outlined
Figure 2. The three engines, from the command a user types to the OCI runtime. A thick outline marks a daemon.

Engines with a Daemon: Docker and containerd

Docker and containerd are daemons, processes that run from boot to shutdown and receive requests on a Unix socket. The docker command, ctr, the low-level client that comes with containerd, and nerdctl, a client of containerd with the commands of docker, are only clients. When a user types docker run, the client sends the request to dockerd through /var/run/docker.sock.

dockerd handles the images and the network and hands the container itself to containerd, a second daemon, which starts a shim process for the container. The shim calls the runtime, which exits once the container runs, and stays the parent of the container process. On the Docker host:

root@qemuarm64:~# ps -o pid,ppid,user,args
PID   PPID  USER     COMMAND
  216     1 root     /usr/bin/containerd
  253     1 root     /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
  527     1 root     /usr/bin/docker run --rm --name frame-counter-image frame-counter-image:latest
  546     1 root     /usr/bin/containerd-shim-runc-v2 -namespace moby -id 903edc2cd7a7[...] -address /run/containerd/containerd.sock
  572   546 1000     /usr/bin/frame-counter camera0
[...]

frame-counter, process 572, is a child of the shim, and neither dockerd nor the docker run client is its parent. On the containerd host there is no dockerd. The client, here ctr, talks to containerd directly, and the shim is again the parent of the container. Because of the shim, the container does not depend on its client. Stopping a first version of the systemd service that ran ctr run, with no stop command of its own, killed the client and left the container running:

root@qemuarm64:~# ctr task ls
TASK             PID    STATUS
frame-counter    331    RUNNING
root@qemuarm64:~# systemctl stop frame-counter-ctr
root@qemuarm64:~# systemctl is-active frame-counter-ctr
failed
root@qemuarm64:~# ctr task ls
TASK             PID    STATUS
frame-counter    331    RUNNING

A service that runs a container through a daemon must therefore stop the container through the daemon, which the Yocto article shows. In both engines, whoever can write to the socket controls every container of the device.

Podman, an Engine without a Daemon

Podman runs without a daemon. The podman command does the work of the engine itself, starts conmon, a small monitor process that calls the runtime and then keeps the output and the exit status of the container, and exits. Only conmon stays, one per container. On the Podman host, for the container that systemd starts at boot:

root@qemuarm64:~# ps -o pid,ppid,user,args
PID   PPID  USER     COMMAND
  320     1 root     /usr/bin/conmon --api-version 1 -c e198667e84ab[...] -r /usr/bin/crun [...]
  322   320 1000     /usr/bin/frame-counter camera0
[...]

conmon is the parent of the application and names the runtime it uses, -r /usr/bin/crun. No process accepts requests for all containers, and the cgroup of the container sits under the systemd service that started it, container-frame-counter-image.service. An ordinary user can also run Podman, as the last section shows.

Kubernetes, and System Containers

Kubernetes does not call an engine directly. It talks to it through the Container Runtime Interface, CRI, which containerd implements with a plugin and CRI-O implements as an engine made only for Kubernetes, and meta-virtualization packages both. K3s, a lightweight Kubernetes distribution that meta-virtualization provides as the k3s and k3s-node profiles, embeds its own containerd. On a device, Kubernetes makes sense when a fleet is managed as a cluster, and otherwise an engine with systemd services is simpler.

The containers of this article are application containers, one application with sometimes a few helpers and no init system. System containers run a whole distribution with its own init, like a light virtual machine that shares the kernel. LXC creates them, Incus, the incus profile of meta-virtualization, manages LXC containers and virtual machines, and systemd-nspawn, in the systemd-container package of OE-core, boots a directory or a disk image as a container under systemd. They suit a device that must host a complete second system, a legacy distribution for instance, more than one that runs applications.

PID 1 and Signals

In its PID namespace, the first process of a container is process 1, and the kernel treats it like the init of a system. Signals sent from outside the namespace reach it only if it has installed a handler for them, except SIGKILL and SIGSTOP, as pid_namespaces(7) documents. Our application has no handler for SIGTERM, so a stop request that sends SIGTERM does nothing. With a service whose stop command is ctr task kill --signal SIGTERM frame-counter:

root@qemuarm64:~# systemctl stop frame-counter-ctr; ctr task ls
TASK             PID    STATUS
frame-counter    311    RUNNING

Docker and Podman behave the same way. They send SIGTERM, wait ten seconds by default, then send SIGKILL, so the application never gets to shut down cleanly. Either the application handles SIGTERM, or it runs behind a small init process that becomes PID 1, forwards signals and reaps zombie processes, such as tini, installed with the containerd profile of meta-virtualization, or catatonit, installed with Podman. docker run --init and podman run --init add one without changing the image.

Users in Rootful and Rootless Containers

Docker and Podman started by root are rootful. The container shares the user namespace of the host, as the namespace listing above shows, so a user ID inside the container is the same user ID on the host. Our image runs as user 1000. After a user app was created on the Podman host, it got user ID 1000, and ps shows the container started at boot as belonging to that user:

  323     1 root     /usr/bin/conmon --api-version 1 -c e946307f87d1[...]
  325   323 app      /usr/bin/frame-counter camera0

Root inside a rootful container is root on the host. Anyone who can talk to the engine can choose the user of a container, mount the host file system into it and read or change any file, so access to the socket of Docker or containerd is equivalent to root on the device.

In rootless mode, the engine runs as an ordinary user and creates the containers in a new user namespace. Root inside the container maps to that user on the host, and the other user IDs of the container map to a range reserved for the user in /etc/subuid and /etc/subgid. On the rootless Podman host of our article on rootless Docker and Podman, user app runs the application from a systemd user service:

app@qemuarm64:~$ grep app /etc/subuid
app:100000:65536
app@qemuarm64:~$ podman top frame-counter user huser pid hpid
USER        HUSER       PID         HPID
app         100999      1           864
app@qemuarm64:~$ podman unshare cat /proc/self/uid_map
         0       1000          1
         1     100000      65536

The map says that user 0 of the container is user 1000 of the host, and that users 1 to 65536 are users 100000 to 165535. The application, user 1000 in the container, is user 100999 on the host, an ID that belongs to nobody. A process that escapes the container has no more rights than that.

Rootless user namespace: container UID 0 maps to host UID 1000, container UIDs 1 to 65536 map to 100000 to 165535
Figure 3. The user namespace of a rootless container, as /proc/self/uid_map describes it.

Summing Up

When choosing an engine for a device, weigh what it adds to the image, from dockerd, containerd and a client for Docker down to a single podman program and conmon, and use crun rather than runc where storage is tight. Check who keeps a container alive and who can control it through a socket, stop the applications through the engine, and handle SIGTERM in them or start them with --init.

Run the engine rootless when the applications do not need root, and treat access to the socket of a rootful engine as root on the device. Our article on containers with Yocto builds the three engines into an image and runs the same application on each.

Which engine do your devices run, and why? Tell us in the comments.

Share this post on:

Leave a Reply

Your email address will not be published. Required fields are marked *