TExcelTAD
Home › Docker › Under the Hood: dockerd, containerd & runc

Under the Hood: dockerd, containerd & runc

When you type docker run nginx, the docker command doesn't start the container itself. It hands the request down a chain of programs, each with one job. Knowing that chain explains a lot of everyday behaviour: why containers survive a Docker upgrade, why Kubernetes runs your Docker-built images without Docker, and what an error mentioning containerd or runc is actually telling you.

The chain of command

text
docker CLI ──REST over /var/run/docker.sock──▶ dockerd
                                                  │ gRPC over /run/containerd/containerd.sock
                                                  ▼
                                              containerd ──▶ containerd-shim-runc-v2 (one per container)
                                                                   │ runs once
                                                                   ▼
                                                                  runc ──▶ your process (PID 1 in the container)
Component Job
docker CLI Turns your command into HTTP calls to the Docker Engine API. It can talk to a local or a remote engine (docker context, DOCKER_HOST).
dockerd (Docker Engine) The Docker-specific features: the API, builds (BuildKit), networks and port publishing, volumes, Compose's backend, logging drivers. It delegates running containers to containerd.
containerd A general container runtime daemon (a CNCF project): pulls and stores images, unpacks layers into snapshots, and manages container lifecycles. Docker and Kubernetes both use it.
containerd-shim-runc-v2 A small process per container. It calls runc, then stays as the container's parent: holds its stdin/stdout, collects its exit code, and keeps it independent of the daemons.
runc The low-level runtime. Reads an OCI bundle, asks the kernel for namespaces and cgroups, sets up the root file system, starts your process with execve, and then exits.

The split is why dockerd and containerd can restart (an upgrade, a crash) without killing your containers: the running processes hang off their shims, not off the daemons. With "live-restore": true in /etc/docker/daemon.json, Docker reconnects to them when it comes back. This model walks the chain and then restarts the daemons:

python · try it yourself
class Process:
    def __init__(self, name, parent=None):
        self.name, self.parent, self.alive = name, parent, True

    def tree(self, everyone, depth=0):
        state = "" if self.alive else "  (stopped)"
        print("  " * depth + self.name + state)
        for p in everyone:
            if p.parent is self:
                p.tree(everyone, depth + 1)

init = Process("systemd (PID 1)")
dockerd = Process("dockerd", init)
containerd = Process("containerd", init)
everyone = [init, dockerd, containerd]

def docker_run(image):
    print(f"$ docker run -d {image}")
    print("  CLI -> dockerd: POST /containers/create, POST /containers/{id}/start")
    print("  dockerd -> containerd: create container + task (gRPC)")
    shim = Process(f"containerd-shim-runc-v2 ({image})", init)
    print("  containerd -> shim -> runc create/start: namespaces, cgroups, rootfs, execve")
    app = Process(f"{image} entrypoint", shim)
    print("  runc exits; the shim stays as the container's parent")
    everyone.extend([shim, app])

docker_run("nginx")
docker_run("redis")
print()
init.tree(everyone)

print("\n# systemctl restart docker containerd")
dockerd.alive = containerd.alive = False
running = [p.name for p in everyone if p.alive and "entrypoint" in p.name]
print("containers still running:", running)
dockerd.alive = containerd.alive = True
print("daemons back; with live-restore, dockerd re-attaches to", len(running), "containers")
$ docker run -d nginx
  CLI -> dockerd: POST /containers/create, POST /containers/{id}/start
  dockerd -> containerd: create container + task (gRPC)
  containerd -> shim -> runc create/start: namespaces, cgroups, rootfs, execve
  runc exits; the shim stays as the container's parent
$ docker run -d redis
  CLI -> dockerd: POST /containers/create, POST /containers/{id}/start
  dockerd -> containerd: create container + task (gRPC)
  containerd -> shim -> runc create/start: namespaces, cgroups, rootfs, execve
  runc exits; the shim stays as the container's parent

systemd (PID 1)
  dockerd
  containerd
  containerd-shim-runc-v2 (nginx)
    nginx entrypoint
  containerd-shim-runc-v2 (redis)
    redis entrypoint

# systemctl restart docker containerd
containers still running: ['nginx entrypoint', 'redis entrypoint']
daemons back; with live-restore, dockerd re-attaches to 2 containers

Seeing it on a real host

On a Linux machine running Docker Engine you can see every layer of the chain:

bash
docker run -d --name web nginx:1.27
ps -eo pid,ppid,cmd --forest | grep -E 'containerd|nginx' | grep -v grep
docker info --format '{{.DefaultRuntime}}'
sudo ctr --namespace moby containers list      # Docker's containers, as containerd sees them

Sample output (abridged, PIDs and IDs will differ):

text
   812       1 /usr/bin/containerd
  4127       1 /usr/bin/containerd-shim-runc-v2 -namespace moby -id 3f9c2a7e5b1d... -address /run/containerd/containerd.sock
  4149    4127  \_ nginx: master process nginx -g daemon off;
  4190    4149      \_ nginx: worker process
runc
CONTAINER                                                           IMAGE    RUNTIME
3f9c2a7e5b1d8c0e4a6f2d9b7c5e1a3f8d0b2c4e6a8f1d3b5c7e9a0b2d4f6a8c    -        io.containerd.runc.v2

Notice that nginx's parent is the shim, and the shim's parent is PID 1, not dockerd. Docker keeps its containers in a containerd namespace called moby (a containerd grouping, unrelated to Linux namespaces); Kubernetes uses k8s.io, so the two never see each other's containers on a shared host. ctr is containerd's bare debugging CLI: fine for looking, not meant for daily use.

Note: Since Docker Engine 29, fresh installs also store images in containerd (the "containerd image store") instead of Docker's older overlay2 graph driver. Upgraded installs keep the old store until you switch. Either way, docker images works the same.

The OCI specifications

The pieces can be swapped because the interfaces between them are open standards from the Open Container Initiative (OCI), founded in 2015 with Docker's image format and runtime as the starting point:

Spec Defines Who uses it
Image spec An image = a manifest listing a config JSON (entrypoint, env, user, …) and a list of compressed layer tarballs, all addressed by sha256 digest. An index points to one manifest per platform (linux/amd64, linux/arm64). docker build, BuildKit, Buildah, Kaniko produce it; every runtime consumes it
Distribution spec The registry HTTP API to push and pull those blobs and manifests Docker Hub, GHCR, ECR, Harbor, and the oci:// charts in Helm
Runtime spec A bundle: a directory with config.json (process, mounts, namespaces, cgroup limits) and a rootfs/ runc, crun, youki, gVisor's runsc, Kata Containers

So containerd turns an image (image spec) into a bundle (runtime spec), and any compliant low-level runtime can start it. This model does that translation for one container: it merges the image config with your docker run flags into the parts of config.json that runc reads.

python · try it yourself
import json

image_config = {                        # from the image (what the Dockerfile set)
    "User": "101", "WorkingDir": "/app",
    "Env": ["PATH=/usr/local/bin:/usr/bin:/bin", "APP_ENV=production"],
    "Entrypoint": ["python", "-m", "shop"], "Cmd": ["--port", "8000"],
}
run_flags = {"memory": "512m", "cpus": 1.5, "pids_limit": 200, "env": ["LOG_LEVEL=debug"]}

def to_bytes(size):
    units = {"k": 1024, "m": 1024 ** 2, "g": 1024 ** 3}
    return int(size[:-1]) * units[size[-1]] if size[-1] in units else int(size)

period = 100_000                         # microseconds; --cpus=1.5 means 1.5 periods of CPU per period
config = {
    "ociVersion": "1.2.0",
    "process": {
        "user": {"uid": int(image_config["User"]), "gid": 0},
        "args": image_config["Entrypoint"] + image_config["Cmd"],
        "env": image_config["Env"] + run_flags["env"],
        "cwd": image_config["WorkingDir"],
    },
    "root": {"path": "rootfs", "readonly": False},
    "hostname": "3f9c2a7e5b1d",
    "linux": {
        "namespaces": [{"type": t} for t in ["pid", "network", "ipc", "uts", "mount", "cgroup"]],
        "resources": {
            "memory": {"limit": to_bytes(run_flags["memory"])},
            "cpu": {"quota": int(run_flags["cpus"] * period), "period": period},
            "pids": {"limit": run_flags["pids_limit"]},
        },
    },
}
print(json.dumps(config, indent=2))
{
  "ociVersion": "1.2.0",
  "process": {
    "user": {
      "uid": 101,
      "gid": 0
    },
    "args": [
      "python",
      "-m",
      "shop",
      "--port",
      "8000"
    ],
    "env": [
      "PATH=/usr/local/bin:/usr/bin:/bin",
      "APP_ENV=production",
      "LOG_LEVEL=debug"
    ],
    "cwd": "/app"
  },
  "root": {
    "path": "rootfs",
    "readonly": false
  },
  "hostname": "3f9c2a7e5b1d",
  "linux": {
    "namespaces": [
      {
        "type": "pid"
      },
      {
        "type": "network"
      },
      {
        "type": "ipc"
      },
      {
        "type": "uts"
      },
      {
        "type": "mount"
      },
      {
        "type": "cgroup"
      }
    ],
    "resources": {
      "memory": {
        "limit": 536870912
      },
      "cpu": {
        "quota": 150000,
        "period": 100000
      },
      "pids": {
        "limit": 200
      }
    }
  }
}

A real config.json has much more (mounts for /proc, /dev and your volumes, capabilities, seccomp and AppArmor profiles, masked paths), but these are the fields that map one to one onto what you already know: ENTRYPOINT + CMD become args, USER becomes uid, --memory becomes a cgroup limit.

You can even run a bundle with runc directly, no Docker involved, as runc's own README shows:

bash
mkdir -p demo/rootfs && cd demo
docker export "$(docker create alpine:3.22)" | tar -C rootfs -xf -   # borrow a root file system
runc spec                                                          # writes a default config.json (runs sh)
sudo runc run demo1                                                # a shell inside the new container

Namespaces and cgroups at a glance

runc's real work is a handful of kernel calls. The container is an ordinary process with:

  • namespaces for what it can see: its own PIDs (pid), network interfaces and ports (net), mounts and root file system (mnt), hostname (uts), IPC objects (ipc), and optionally user IDs (user, for rootless containers);
  • cgroups (v2 on current distributions) for what it can use: memory.max, cpu.max, pids.max, I/O weights. docker run --memory, --cpus and --pids-limit end up as those files under /sys/fs/cgroup;
  • plus capabilities, seccomp and an LSM profile (AppArmor or SELinux) to narrow what root inside the container may do (see Container Security).

The kernel side is covered in depth in Virtualization & Containers in the Operating Systems course, and the hands-on administration (systemd units, cgroup slices, inspecting /proc) in Linux Server Administration.

Kubernetes: containerd without Docker

Kubernetes never needed dockerd's extras (its own networking, volumes and build). The kubelet talks to a runtime through the Container Runtime Interface (CRI), a gRPC API. containerd implements CRI with a built-in plugin, and CRI-O is a CRI runtime written just for Kubernetes:

text
Docker host:      docker CLI → dockerd → containerd → shim → runc
Kubernetes node:          kubelet ─CRI→ containerd → shim → runc     (or kubelet ─CRI→ CRI-O → runc/crun)

Kubernetes 1.24 (2022) removed dockershim, the adapter that let the kubelet drive dockerd. That sounded alarming but changed little for users: nodes run containerd or CRI-O, and the images you build with Docker are OCI images that any of them can run. What changed is debugging on a node: there is no docker ps, you use crictl instead:

bash
sudo crictl ps
sudo crictl images
sudo crictl logs <container-id>

Sample output of crictl ps (abridged):

text
CONTAINER      IMAGE          CREATED        STATE     NAME       ATTEMPT   POD ID         POD
a41f0c2d9e3b7  4f2c1e8a9b0d6  2 hours ago    Running   api        0         9be71d3c5a2f0  api-7c9d6b5f4-x2kqp

Runtimes can also be swapped per workload: Kubernetes' RuntimeClass lets a Pod ask for a sandboxed runtime such as gVisor or Kata Containers (a lightweight VM per Pod) for untrusted code, while everything else uses runc.

Tip: When an error mentions OCI runtime create failed it comes from runc, so the problem is usually the container's config: a missing entrypoint binary, a bad mount path, a permission or a cgroup limit. Errors mentioning failed to resolve reference or snapshotter come from containerd's image handling (pulls, registries, disk space).

Go further: Container Isolation: Namespaces, cgroups and Capabilities looks at the same layers from a security reviewer's side.

Test yourself

You restart dockerd and containerd with live-restore enabled. Why do running containers survive?

  1. Docker checkpoints them to disk
  2. Each container's parent is its containerd shim, not the daemons
  3. runc keeps running and restarts them
  4. systemd restarts them instantly

Which OCI specification describes config.json plus a rootfs/ directory?

  1. The image spec
  2. The distribution spec
  3. The runtime spec
  4. The CRI

A Kubernetes node runs containerd and no dockerd. Can it run an image built with docker build?

  1. No, it needs dockershim
  2. Yes: the image is an OCI image, and the kubelet drives containerd through CRI
  3. Only after converting it with ctr convert
  4. Only if the image is pushed to Docker Hub