Skip to content

Containers Under the Hood: Namespaces, cgroups v2, OverlayFS, OCI, containerd, runc, LXC ​

"The Open Container Initiative Runtime Specification aims to specify the configuration, execution environment, and lifecycle of a container." — Open Container Initiative, OCI Runtime Specification (spec.md)

Summary: A container is not a small virtual machine but an ordinary Linux process that the kernel shows a private view of the system (namespaces), meters and caps (cgroups), gives a layered root filesystem (OverlayFS entered with pivot_root) and restricts (capabilities, seccomp); the OCI runtime spec writes that recipe down as a config.json, runc or crun executes it, and containerd, Docker, Podman and the kubelet are the managers stacked on top. Focus: The container definition (process isolation not virtualisation); Linux namespaces one by one (pid net mnt uts ipc user cgroup time namespaces), unshare and nsenter, user namespaces and rootless engines; cgroups v1 vs v2, the cpu memory io pids controllers, cgroup limits and OOM, resource accounting and PSI; OverlayFS as a kernel feature (lowerdir upperdir workdir, copy-up, whiteouts, opaque directories) and the image layers link; chroot vs pivot_root; the OCI runtime spec, OCI image spec and OCI distribution spec, the bundle and its config.json, the container lifecycle; runc, crun and youki; containerd, the shim and the CRI; Docker Engine architecture (dockerd, containerd, runc), Podman daemonless with conmon, LXC/LXD system containers (and Incus); gVisor and Kata as sandboxes, Firecracker microVMs, WebAssembly containers, the container vs VM comparison; PID 1, init systems in containers, tini, signal forwarding and zombie reaping; container networking basics (veth, bridge, netns) with a link to Kubernetes networking; the capabilities and seccomp link; cgroup-aware runtimes (GOMAXPROCS, GOMEMLIMIT, PHP-FPM pm settings): Go container-aware tuning and Laravel in containers (php-fpm process manager vs cgroup limits). Learning goal: Build a container by hand from unshare, a cgroup directory and pivot_root; read any running container's namespaces, cgroup files and overlay mount from the host and explain what each one does; say which process in the dockerd → containerd → shim → runc chain owns what; pick runc, crun, gVisor, Kata or a microVM for a workload; and size a Go service (GOMAXPROCS, GOMEMLIMIT) and a php-fpm pool so that the kernel never has to throttle or OOM-kill them.

This chapter opens the Containers group and owns the kernel and runtime layer. Building images (Dockerfile instructions, layers as a build artefact, caching, registries) is Images & Dockerfiles, which links back here for OverlayFS; docker run flags, volumes and Compose are Running Containers; hardening (dropping capabilities, seccomp and AppArmor/SELinux profiles, rootless engines as a security control, image scanning, Pod Security) is Container Security; the Linux basics underneath (processes, users, permissions, filesystems, systemd) are Linux for Developers, and strace/perf/eBPF are Linux Debugging. Bridges, port publishing and the iptables rules Docker writes are Docker Networking; pod networking and CNI are Kubernetes Networking; the kubelet, control plane and container runtime as a cluster component are Kubernetes Architecture & Setup; requests, limits and QoS classes as a scheduling tool are Resources, Scheduling & Autoscaling; why an organisation adopts containers at all is Containers & Kubernetes. Signals and graceful shutdown in Go are OS Processes, Signals & Graceful Shutdown; goroutines and the scheduler that GOMAXPROCS feeds are Goroutines & Channels.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why containers are processes, not machinesWhy it exists
chroot, namespaces 2.4.19-5.6, cgroups 2.6.24/4.5, OCI 2015, dockershim removal v1.24Where it comes from
What a container actually isContainer definition
The eight namespace typesLinux namespaces
PID 1, init, tini, signals, zombiesPID namespace and PID 1
chroot vs pivot_root, mount propagationMount namespace and the root filesystem
veth, bridge, netnsNetwork namespace
Rootless Docker/Podman, /etc/subuid, hostUsers: falseUser namespaces and rootless
UTS, IPC, cgroup, time namespacesThe smaller namespaces
unshare, nsenter, lsnsunshare and nsenter
v1 hierarchies vs the unified hierarchycgroups v1 vs v2
cpu.max, memory.max, io.max, pids.max, OOM, PSIControllers, limits and OOM
lowerdir, upperdir, workdir, copy-up, whiteoutsOverlayFS
config.json, bundle, lifecycle, image and distribution specsOCI specifications
runc, crun, youkiLow-level runtimes
containerd, shims, CRI, CRI-Ocontainerd, shim and CRI
dockerd vs Podman with conmonDocker Engine and Podman
System containersLXC, LXD and Incus
gVisor, Kata, Firecracker, container vs VMSandboxes and microVMs
Wasm workloads under containerdWebAssembly containers
Where privileges are cutCapabilities and seccomp
GOMAXPROCS, GOMEMLIMIT, php-fpm pm.*Cgroup-aware runtimes
What docker run does, knobs, error messagesMechanics
CodeGo, Laravel
Ten classic problems and their fixesSolving the classic problems
Which runtime, which isolation, which pool modeChoosing
From one VM to many clustersIn architecture
Commands with expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

What the kernel gives a container (all of it is available to any process; a "container" is the combination).

Kernel featureQuestion it answersFiles you can look atSet by
Namespaces (8 types)What can the process see?/proc/<pid>/ns/*clone(2), unshare(2), setns(2)
cgroup v2How much may it use, and how much did it use?/sys/fs/cgroup/<path>/cpu.max, memory.max, memory.events, cpu.statwrites to the cgroup filesystem (runc, systemd)
OverlayFS + pivot_rootWhich files does it have as /?mount | grep overlay, /proc/<pid>/mountinfomount(2), pivot_root(2)
CapabilitiesWhich root powers does it keep?/proc/<pid>/status (CapEff)capset(2), OCI process.capabilities
seccompWhich syscalls may it make?/proc/<pid>/status (Seccomp)seccomp(2), OCI linux.seccomp
no_new_privsCan setuid binaries raise privileges?/proc/<pid>/status (NoNewPrivs)prctl(2), OCI noNewPrivileges

The eight namespaces (namespaces(7); kernel version from clone(2)/unshare(2)).

NamespaceFlagIsolatesIn plain wordsSince Linux
MountCLONE_NEWNSMount pointsOwn mount table, own /2.4.19
UTSCLONE_NEWUTSHostname and NIS domain nameOwn hostname2.6.19
IPCCLONE_NEWIPCSystem V IPC, POSIX message queuesOwn shared memory and semaphores2.6.19
PIDCLONE_NEWPIDProcess IDsOwn PID 1, cannot see host processes2.6.24
NetworkCLONE_NEWNETNetwork devices, stacks, portsOwn lo, eth0, routes, iptables, port 802.6.24
UserCLONE_NEWUSERUser and group IDsRoot inside, nobody outsideusable 3.8
CgroupCLONE_NEWCGROUPCgroup root directory/sys/fs/cgroup starts at its own group4.6
TimeCLONE_NEWTIMEBoot and monotonic clocksOwn uptime offsets (checkpoint/restore)5.6

The runtime stack in one table.

LayerExamplesSpeaksJob
User-facing tooldocker, podman, nerdctl, kubectlCLITurn intent into API calls
Engine / managerdockerd, Podman (libpod), kubeletDocker API, Podman API, Kubernetes APINetworks, volumes, images, restart policy, pods
High-level runtimecontainerd, CRI-OCRI gRPC, containerd APIPull and unpack images (snapshotters), container metadata, tasks
Shim / monitorcontainerd-shim-runc-v2, conmonttRPCParent of the container: stdio, exit code, survives engine restarts
Low-level (OCI) runtimerunc, crun, youki, runsc (gVisor), kata-runtimeOCI runtime spec (config.json + rootfs)Create namespaces, cgroup, mounts, then exec the process and exit
KernelLinuxsyscallsEnforce all of it
A container = one process tree + kernel features around it (no guest kernel)process treePID 1 inside = PID 48213 on the hostnamespaces: what it SEESpid own PID numbers, own PID 1net own interfaces, routes, portsmnt own mount table and rootuts own hostnameipc own SysV IPC, POSIX mqueuesuser own UID/GID map (root inside)cgroup own view of /sys/fs/cgrouptime own boot/monotonic clock offsetscgroup v2: how MUCH it usescpu.max 200000 100000 (2 CPUs)cpu.weight share under contentionmemory.max 512M, then OOM killmemory.high throttle and reclaimio.max per-device bps/iopspids.max fork-bomb ceilingroot filesystem: which FILESOverlayFS: image layers = lowerdir,container layer = upperdir, merged = /entered with pivot_root, not chrootprivileges: what it may ASKcapabilities: a root split into ~40bits; most are droppedseccomp: syscall allow-listno_new_privs, AppArmor/SELinux(Container Security chapter)ONE shared host Linux kernel: every syscall of every container lands here

Why it exists ​

Before containers, running two applications on one Linux server meant they shared everything: the same /usr/lib, the same port space, the same process table, the same memory. One app's library upgrade broke the other; one app's memory leak pushed the other into swap; a compromised app could read the other's files. Virtual machines fixed that by giving each app a whole emulated computer with its own kernel, at the price of booting an operating system per app and reserving its memory up front.

Containers take the opposite trade. The kernel already tracks every process; it is cheap to teach it to show a process a filtered view (its own PID numbers, its own network interfaces, its own mount table) and to account for its CPU, memory and I/O in a group. No second kernel boots, so a container starts in the time it takes to exec a binary and costs the memory its processes actually use. The price is that the isolation boundary is the kernel's system-call interface, shared by every container on the host.

Simpler choiceRicher choiceWhat you buyWhat you pay
Plain process on the hostProcess in namespaces + cgroupOwn view of PIDs, network, files; enforced limitsA runtime to set it up, a bit of kernel bookkeeping
chrootMount namespace + pivot_rootA root the process cannot climb out of; private mountsMust mount /proc, /dev, /sys yourself
Root daemon (rootful Docker)Rootless engine in a user namespaceContainer root is an unprivileged host userSome networking and storage limits, slower networking (user-space network stack)
cgroup v1 (one tree per controller)cgroup v2 (one unified tree)Consistent limits, PSI, safe delegation, memory.highOld tools and runtimes must be v2-aware
runc (shared kernel)gVisor or Kata/FirecrackerA second boundary against kernel exploitsSyscall overhead (gVisor) or a guest kernel per pod (Kata)
Runtime defaults inside the containercgroup-aware tuning (GOMAXPROCS, GOMEMLIMIT, pm.max_children)No throttling surprises, no OOM killsOne more thing to configure and test

The analogy used through this page: an open-plan office with partitions. Every container is a team in one building (the host kernel). Partitions (namespaces) decide what a team can see: its own desk numbers starting at 1 (PID), its own phone extensions (network), its own filing cabinet (mounts), its own name plate (UTS). The facilities budget (cgroup) decides how much electricity and floor space a team may use and sends the bill. The building's security desk (capabilities, seccomp) decides which master keys a team may borrow. Nobody gets a separate building: if the foundations crack (a kernel bug), every team is affected. A VM is a separate building; gVisor is a reception desk that answers most requests without letting the team into the basement; Kata is a prefabricated cabin per team in the car park.

Three common misunderstandings, up front ​

  1. "A container is a lightweight VM." There is no guest kernel. ps on the host lists every container process with a host PID; uname -r inside prints the host's kernel. The OCI runtime spec defines a container as a configuration, an execution environment and a lifecycle for a process, not a machine. See Container definition.
  2. "docker stop sends SIGTERM to my app, so it shuts down cleanly." It sends SIGTERM to PID 1 of the container. The kernel delivers a signal to a namespace's init process only if that process "has established a signal handler" for it (pid_namespaces(7)); a shell or an app that never registered a handler ignores it, and Docker kills it 10 s later. See PID 1.
  3. "The memory limit is just a number Docker shows; my app reads its own setting." memory.max is enforced by the kernel: "If a cgroup's memory usage reaches this limit and can't be reduced, the OOM killer is invoked in the cgroup" (cgroup-v2.rst). The Go runtime and php-fpm do not read it by themselves. See Cgroup-aware runtimes.

Where it comes from ​

WhenWhat happenedSource
Before Linuxchroot in SVr4 and 4.4BSD: change the root for pathname resolution only, "not intended to be used for any kind of security purpose"chroot(2) HISTORY and DESCRIPTION
Linux 2.4.19Mount namespaces, CLONE_NEWNS, the first namespaceclone(2)
Linux 2.3.41pivot_root(2) addedpivot_root(2) HISTORY
Linux 2.6.19UTS and IPC namespacesclone(2)
Linux 2.6.24PID and network namespaces; cgroups with the cpu, cpuacct, cpuset controllersclone(2), cgroups(7)
Linux 3.8User namespaces complete ("the final pieces ... were merged in Linux 3.8"); unprivileged creation allowedclone(2), namespaces(7)
Linux 3.10Work on cgroups v2 begins, behind __DEVEL__sane_behaviorcgroups(7)
LXCUserspace tools combine namespaces, cgroups and pivot_root into "something in the middle between a chroot and a full fledged virtual machine"linuxcontainers.org
22 June 2015OCI launched "by Docker, CoreOS and other leaders in the container industry"opencontainers.org
4 Dec 2015containerd 0.0 (first release)containerd RELEASES.md
Linux 4.5 / 4.6cgroups v2 "made official with the release of Linux 4.5"; cgroup namespaces in 4.6cgroups(7), clone(2)
5 Dec 2017containerd 1.0containerd RELEASES.md
Linux 5.6Time namespacesnamespaces(7), unshare(2)
runc v1.0.0-rc93runc "fully supports cgroup v2 (unified mode)"runc docs/cgroup-v2.md
Debian 11, Ubuntu 21.10Default to cgroup v2 (Fedora since 31, RHEL since 9)runc docs/cgroup-v2.md
Kubernetes v1.24dockershim removed ("announced as a part of the Kubernetes v1.20 release"); the kubelet talks only CRIKubernetes dockershim FAQ
Kubernetes v1.25cgroup v2 support stableKubernetes "About cgroup v2"
5 Nov 2024containerd 2.0 (LTS); config version = 3containerd RELEASES.md, Kubernetes container-runtimes docs
Go 1.25Container-aware GOMAXPROCS by default (with go.mod 1.25+)Go 1.25 release notes, Go blog
Kubernetes v1.35cgroup v1 deprecated; "Kubelet will no longer start on a cgroup v1 node by default"Kubernetes "About cgroup v2"
Kubernetes v1.36User namespaces for pods (hostUsers: false) stableKubernetes user namespaces docs

Two ideas meet in every container. The isolation line runs from chroot through FreeBSD jails and Solaris zones to Linux namespaces: give a process its own view of a resource. The resource control line runs from nice and ulimit to cgroups: account for and cap what a group of processes consumes. LXC combined both on Linux; Docker added the image format and the developer workflow on top, and donated its runtime code to the OCI as runc; the OCI then split the pieces into standards (image format, runtime config, registry API) so that runc, crun, gVisor, Kata, containerd, CRI-O, Podman and Docker can interoperate.

The concept catalogue ​

Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.

Container definition: process isolation, not virtualisation Must-know ​

In plain words: A container is a normal Linux process (and its children) started with a private view of the system, a resource budget and a reduced set of privileges. Take those away and it is just a process.

Common misunderstanding: "Containers virtualise the hardware like a VM, only lighter." Nothing is virtualised: the CPU instructions run natively, memory is ordinary process memory, and every system call goes to the one host kernel. That is why a container cannot run a different kernel (a Linux container on a Mac or Windows machine runs inside a hidden Linux VM: Docker Desktop, Podman machine).

Definition: The OCI runtime spec defines the container through its "configuration, execution environment, and lifecycle"; on Linux the configuration is a config.json that names the namespaces to create or join, the cgroup path and resources, the root filesystem, mounts, capabilities, seccomp filter and the process to run. In practice the word covers three things that are easy to confuse: the image (files + metadata, the subject of Images & Dockerfiles), the bundle (an unpacked rootfs + config.json on one host) and the running container (the process tree the runtime created from the bundle).

text
docker run -d --memory 512m --cpus 2 ghcr.io/acme/orders-api:1.4.2
1  image pulled and unpacked into snapshot layers (containerd snapshotter, OverlayFS)
2  container layer created (an empty upperdir) and an OCI bundle generated: rootfs + config.json
3  shim started; it runs `runc create`: clone() with CLONE_NEWPID|NEWNS|NEWNET|NEWUTS|NEWIPC|NEWCGROUP
4  runc writes cpu.max = "200000 100000", memory.max = 536870912 into the new cgroup
5  runc mounts the overlay as the root, pivot_root()s into it, mounts /proc, /dev, /sys
6  runc drops capabilities, sets no_new_privs, loads the seccomp filter
7  `runc start`: execve("/orders-api") as PID 1 of the new PID namespace; runc exits
8  ps on the host: /orders-api with host PID 48213, parent containerd-shim-runc-v2

Real scenarios:

  • top on a Kubernetes node shows every pod's processes; a CPU spike "inside a container" is a host process you can perf or strace from the node.
  • A container image built for Linux runs on any distribution with a compatible kernel, but an app that needs a newer kernel feature (io_uring, a new syscall) fails on an old host whatever the image contains.
  • uname -r in a container prints the host kernel version, which surprises people who expect the image's distribution kernel.
  • Docker Desktop on macOS runs containers in a Linux VM; file sharing and networking cross that VM boundary, which is why bind mounts are slower there than on Linux.
ProductWhat "container" means there
Docker EngineA process created by runc from an image, managed through dockerd and containerd
PodmanSame OCI container, created by crun or runc via conmon, no daemon
KubernetesA container inside a pod; all containers of a pod share network and IPC namespaces (the pause/sandbox container holds them)
LXC / LXD / IncusA system container: a whole distribution with its own init (systemd) running in namespaces
gVisor / KataAn OCI container whose process runs on a user-space kernel (gVisor) or inside a lightweight VM (Kata)
Docker Desktop, Podman machineLinux containers inside a Linux VM on macOS/Windows

Fix / how to use it: reason about containers as processes. Debug them with host tools (ps, nsenter, cat /sys/fs/cgroup/...), size them like processes (real RSS, real threads) and secure them like processes that share a kernel with everything else on the node.

Linux namespaces Must-know ​

In plain words: A namespace wraps one kind of global resource (process IDs, network stack, mounts...) so that processes inside see their own copy. There are eight kinds, used together or separately.

Common misunderstanding: "A container has one namespace." It has one of each kind it was given, and each can be shared independently: Kubernetes containers in one pod share the network namespace but not the mount namespace; docker run --pid=host shares the host PID namespace only.

Definition: namespaces(7): "A namespace wraps a global system resource in an abstraction that makes it appear to the processes within the namespace that they have their own isolated instance of the global resource." Three system calls manage them: clone(2) creates a process in new namespaces (CLONE_NEW* flags), unshare(2) moves the caller into new ones, setns(2) joins an existing one through a file descriptor for /proc/<pid>/ns/<type>. Creating namespaces "in most cases requires the CAP_SYS_ADMIN capability", but "User namespaces are the exception: since Linux 3.8, no privilege is required to create a user namespace." A namespace lives while a process is in it or a file descriptor or bind mount holds its /proc/<pid>/ns file open.

text
Same host, two processes
host shell  $ readlink /proc/$$/ns/net      -> net:[4026531840]   (the initial network namespace)
container   $ readlink /proc/1/ns/net       -> net:[4026532301]
host        $ readlink /proc/48213/ns/net   -> net:[4026532301]   (same inode = same namespace)
host        $ readlink /proc/48213/ns/pid   -> pid:[4026532299]   (48213 is PID 1 in there)
-> "is this the same namespace?" = "is the inode number the same?"

Real scenarios:

  • A sidecar (log shipper, Envoy) sees the app's localhost:8080 because the pod's containers share one network namespace.
  • kubectl debug --target=app starts an ephemeral container in the app container's PID namespace so ps shows the app's processes.
  • A CI job runs docker run --network host to reach a database on the runner; the container now shares the host network namespace and port space.
  • lsns on a node shows hundreds of net namespaces: one per pod, plus the host's.
ProductHow it uses namespaces
runc / crunCreate or join the namespaces listed in linux.namespaces of config.json (a path means join)
DockerNew pid, net, mnt, uts, ipc and (cgroup v2) cgroup namespaces per container; user namespace only with userns-remap or rootless; --pid/--network/--ipc/--uts=host or container:<name> to share
KubernetesOne pod sandbox holds net, ipc and (optionally) uts namespaces shared by all containers; shareProcessNamespace: true shares PID; hostUsers: false adds a user namespace
PodmanSame as Docker plus pods (shared infra container); rootless always uses a user namespace
LXC / IncusAll namespaces including user (unprivileged containers are the default recommendation)

Fix / how to use it: when something "works on the host but not in the container" (or the reverse), name the namespace: DNS and ports are net, mounts and files are mnt, process lists are pid, permissions on bind mounts are user. Then compare /proc/<pid>/ns/* inodes between the two sides.

PID namespace and PID 1: init, tini, signal forwarding, zombie reaping Must-know ​

In plain words: The first process in a new PID namespace becomes PID 1, the namespace's "init". Init has two special jobs in Linux: it adopts orphaned processes (and must reap them when they die), and the kernel protects it from signals it did not ask for.

Common misunderstanding: "PID 1 in a container behaves like any other process." Two kernel rules differ. pid_namespaces(7): "Only signals for which the 'init' process has established a signal handler can be sent to the 'init' process by other members of the PID namespace", and from an ancestor namespace (the host, where docker stop acts) likewise "only if the 'init' process has established a handler for that signal", except that "SIGKILL or SIGSTOP are treated exceptionally: these signals are forcibly delivered when sent from an ancestor PID namespace." So an app without a SIGTERM handler, running as PID 1, ignores docker stop. And "If the 'init' process of a PID namespace terminates, the kernel terminates all of the processes in the namespace via a SIGKILL signal."

Definition: Orphans are reparented: "When a child process becomes orphaned, it is reparented to the 'init' process in the PID namespace of its parent (unless one of the nearer ancestors of the parent employed the prctl(2) PR_SET_CHILD_SUBREAPER command ...)". A process that has exited but has not been wait()ed for is a zombie: it holds a PID until its parent reaps it. An init for containers is a tiny PID 1 that forwards signals to its single child and reaps everything else. tini: "All Tini does is spawn a single child ... and wait for it to exit all the while reaping zombies and performing signal forwarding"; it "ensures that the default signal handlers work for the software you run". Docker's docker run --init injects one (--init: "Run an init inside the container that forwards signals and reaps processes"). Full init systems (systemd, s6-overlay, supervisord) are a different choice: they manage several services and belong in system containers or deliberate multi-process images.

text
Shell-form CMD: "CMD php artisan queue:work" -> /bin/sh -c "php artisan queue:work"
1  sh is PID 1 (no SIGTERM handler), php is PID 7
2  docker stop -> SIGTERM to PID 1 -> kernel drops it (init without a handler)
3  10 s later docker sends SIGKILL -> sh dies -> kernel SIGKILLs php mid-job
With tini: ENTRYPOINT ["tini","--"] CMD ["php","artisan","queue:work"]
1  tini PID 1 (handles SIGTERM), php PID 7
2  docker stop -> SIGTERM -> tini forwards it to php -> worker finishes the job, exits 0
3  tini reaps php and any orphaned grandchildren, then exits with php's status

Real scenarios:

  • A Node.js or PHP CLI app run as PID 1 without a handler takes exactly 10 s to stop in Docker and 30 s (the default grace period) in Kubernetes, every deploy.
  • A container that shells out to git or ImageMagick and never reaps (the parent spawns and forgets) accumulates <defunct> zombies until pids.max is hit and fork fails.
  • A Go binary as PID 1 with signal.NotifyContext(ctx, syscall.SIGTERM) installs a handler, so it receives SIGTERM; it still never reaps grandchildren it did not start, which matters only if it spawns processes.
  • Killing the init of a pod's sandbox kills every process in that PID namespace at once (the kernel rule above), which is how runtimes tear containers down reliably.
ProductPID 1 handling
DockerYour ENTRYPOINT/CMD is PID 1; --init adds docker-init (tini) as PID 1
PodmanSame; --init adds a container init (binary chosen with --init-path)
KubernetesContainer entrypoint is PID 1; no init flag; shareProcessNamespace: true makes the pause container PID 1 and reaper for the pod
tini / dumb-initMinimal inits; tini can be a subreaper with -s when not PID 1
LXC / Incus system containerssystemd (or another full init) is PID 1, as on a VM
Go runtimeNot an init; handles signals you signal.Notify, never reaps processes it did not start

Fix: use exec-form ENTRYPOINT/CMD, end wrapper scripts with exec "$@", handle SIGTERM in the app, and add --init/tini (or shareProcessNamespace) whenever the process spawns children. Signal handling in Go is covered in OS Processes, Signals & Graceful Shutdown; the Dockerfile side (exec vs shell form, STOPSIGNAL) in Images & Dockerfiles.

Mount namespace and the root filesystem: chroot vs pivot_root Important ​

In plain words: A mount namespace gives a process its own list of mounts. The runtime mounts the image as the new root, switches the process into it with pivot_root, and unmounts the host's filesystem so it is gone, not just hidden.

Common misunderstanding: "A container is a fancy chroot." chroot only changes where pathname resolution starts, for one process. chroot(2) says it "changes an ingredient in the pathname resolution process and does nothing else. In particular, it is not intended to be used for any kind of security purpose", and shows how "the superuser can escape from a 'chroot jail'" with mkdir foo; chroot foo; cd ... The host's mounts are all still there.

Definition: pivot_root(2) "changes the root mount in the mount namespace of the calling process. More precisely, it moves the root mount to the directory put_old and makes new_root the new root mount." Its rules: new_root "must be a path to a mount point, but can't be '/'", put_old "must be at or underneath new_root", and the propagation type of the involved mounts must not be shared. After the pivot the runtime unmounts put_old (lazily, MNT_DETACH), so the old root is unreachable. The man page documents the shortcut runtimes use, pivot_root(".", ".") followed by umount2(".", MNT_DETACH). Mount propagation (shared, private, slave, unbindable, mount_namespaces(7)) decides whether mounts made inside leak out; runtimes make / rprivate first, and Kubernetes mountPropagation: Bidirectional deliberately reopens it for CSI drivers.

text
runc init inside the new mount namespace
1  mount --make-rprivate /                    (nothing propagates back to the host)
2  mount overlay (lowerdir=layers, upperdir=container layer) on .../rootfs
3  bind-mount rootfs onto itself              (pivot_root needs a mount point)
4  mount proc, sysfs, tmpfs /dev, devpts, mqueue, cgroup2 under rootfs; bind volumes
5  chdir(rootfs); pivot_root(".", "."); umount2(".", MNT_DETACH)   -> host root gone
6  apply maskedPaths (/proc/kcore ...) and readonlyPaths (/proc/sys ...), then exec

Real scenarios:

  • A container escape CVE that relied on a host path being reachable through /proc/self/root only works when the runtime left the old root mounted; pivot_root + detach closes that.
  • mount inside a container shows a short list starting with overlay on / type overlay; the host's mounts are not in its table.
  • A CSI driver needs Bidirectional propagation so volumes it mounts inside its pod appear on the node for other pods.
  • Build tools that fall back to chroot when unprivileged (some debootstrap workflows) do not give container-grade isolation.
ProductRoot filesystem setup
runcpivot_root by default; --no-pivot falls back to MS_MOVE + chroot (needed on a ramfs root, e.g. some installers)
crun / youkipivot_root
Docker / PodmanOverlay rootfs from the image store, volumes as bind mounts, --read-only makes the rootfs read-only
KubernetesSame via CRI; readOnlyRootFilesystem, mountPropagation per volume mount
LXC"Chroots (using pivot_root)" is listed among its kernel features

Fix: never rely on chroot for isolation; when writing tooling, use a mount namespace + pivot_root (the Lab has a 15-line version) or, better, an OCI runtime.

Network namespace: veth, bridge, netns Important ​

In plain words: A new network namespace has only a loopback interface that is down. A container gets connectivity because the runtime (or a CNI plugin) creates a virtual cable, a veth pair, puts one end inside as eth0, plugs the other end into a bridge on the host and adds NAT rules.

Common misunderstanding: "Containers on one host talk to each other through the host's localhost." Each has its own localhost; they talk over the bridge using their own IPs (Docker's default bridge gives 172.17.0.x), or share one namespace (a Kubernetes pod, --network container:<name>).

Definition: network_namespaces(7): network namespaces "provide isolation of the system resources associated with networking: network devices, IPv4 and IPv6 protocol stacks, IP routing tables, firewall rules, the /proc/net directory ..., port numbers (sockets), and so on." veth(4): "veth devices are always created in interconnected pairs", with ip link add <p1-name> type veth peer name <p2-name>; a packet sent into one end comes out of the other, even across namespaces. A Linux bridge is a virtual switch joining the host ends. ip netns (iproute2) names namespaces by bind-mounting them under /var/run/netns, which is what the OCI path field joins.

text
Bridge-mode container receiving a request on host port 8080 (docker run -p 8080:80)
1  client -> host eth0:8080
2  iptables DNAT (nat PREROUTING) 8080 -> 172.17.0.2:80
3  route to docker0 (bridge, 172.17.0.1/16) -> vethab12 (host end)
4  veth pair -> eth0 inside the container's netns -> nginx listening on :80
5  reply: eth0 -> veth -> docker0 -> conntrack reverses the DNAT -> client
Egress: container -> docker0 -> MASQUERADE (SNAT to the host IP) -> internet

Real scenarios:

  • An app binds 127.0.0.1:8080 inside the container and -p 8080:8080 does not work: the DNAT target is the container's eth0 address, not its loopback. Bind 0.0.0.0.
  • MTU mismatch: the host uses a 1450-byte overlay or VPN, the bridge and veth use 1500, large TLS responses hang.
  • A distroless container has no ip or ss; nsenter --target <pid> --net ss -ltnp runs the host's ss in its network namespace.
  • Kubernetes pods get one IP per pod: the CNI plugin creates the netns' veth (or another device) instead of Docker's bridge.
ProductDefault container networking
Dockerbridge driver: docker0, one veth per container, iptables/nftables NAT; also host, none, macvlan, overlay
Podman (root)Netavark bridge; rootless: pasta (user-space network stack, since Podman 5 the default)
KubernetesCNI plugin (Calico, Cilium, Flannel ...) sets up the pod netns; one IP per pod
containerd (nerdctl)CNI plugins directly
LXC / Incuslxcbr0 / incusbr0 bridge with veth, or macvlan/physical

Fix: learn to read the path packet by packet (ip -n, nsenter --net, iptables -t nat -L -n -v, conntrack -L). The full models (port publishing rules, embedded DNS, overlay networks, CNI, Services, kube-proxy) are taught in Docker Networking and Kubernetes Networking.

User namespaces and rootless containers Must-know ​

In plain words: A user namespace maps a range of user IDs inside to a different range outside. The process can be UID 0 (root) inside while being an ordinary unprivileged UID on the host, so "root in the container" stops meaning "root on the machine".

Common misunderstanding: "Docker containers already run in a user namespace." By default (rootful Docker) they do not: UID 0 in the container is UID 0 on the host, held back only by dropped capabilities and seccomp. A user namespace is added only with userns-remap, rootless mode, Podman rootless, or Kubernetes hostUsers: false.

Definition: user_namespaces(7): a process created in a new user namespace "starts out with a complete set of capabilities in the new user namespace", but "that process has no capabilities in the parent". The mapping is written to /proc/<pid>/uid_map and gid_map as ID-inside ID-outside length. Unprivileged users may map only their own UID unless the setuid helpers newuidmap/newgidmap grant the subordinate ranges listed in /etc/subuid and /etc/subgid. unshare(1)'s example: /etc/subuid holds 1000:100000:65536, and inside the namespace a file chowned to 1:1 appears on the host as 100000 100000. Rootless engines run the daemon and containers inside such a namespace: Docker's rootless mode "executes the Docker daemon and containers inside a user namespace", unlike userns-remap where "the daemon itself is running with root privileges"; it needs "newuidmap and newgidmap" and at least 65,536 subordinate IDs.

text
Rootless Podman, user alice (uid 1000), /etc/subuid: alice:100000:65536
1  podman run alpine id         -> uid=0(root) inside
2  uid_map inside:              0 1000 1 / 1 100000 65535
3  on the host: ps -o user      -> alice (the container's root is uid 1000)
4  container's uid 33 (www-data) writes a file -> host sees owner 100032
5  container root tries to load a kernel module -> EPERM: no CAP_SYS_MODULE in the initial namespace

Real scenarios:

  • A CI runner builds images with rootless BuildKit or Podman so a malicious build step cannot become root on the shared runner.
  • Bind-mounting a host directory into a rootless container shows files owned by nobody (unmapped IDs), and writes fail until you podman unshare chown or use idmapped mounts.
  • Kubernetes hostUsers: false (stable in v1.36) gives each pod its own mapping, so a container breakout lands as an unprivileged host UID.
  • Rootless containers cannot bind host ports below 1024 by default (net.ipv4.ip_unprivileged_port_start) and their networking runs through a user-space stack (pasta, slirp4netns).
ProductUser namespace support
DockerOff by default; userns-remap (daemon still root); rootless mode (daemon and containers unprivileged)
PodmanRootless by design; --userns=auto, keep-id, podman unshare
Kubernetesspec.hostUsers: false per pod (stable v1.36), needs runtime + kernel support for idmapped mounts
runc / crunlinux.uidMappings/gidMappings in config.json; runc spec --rootless
LXC / IncusUnprivileged containers (mapped root) are the recommended default

Fix: prefer rootless engines on developer machines and shared CI, and hostUsers: false on clusters that support it. Hardening details (capability sets, seccomp profiles, AppArmor/SELinux, Pod Security) are in Container Security.

The smaller namespaces: UTS, IPC, cgroup, time Good to know ​

In plain words: Four namespaces isolate one small thing each: the hostname (UTS), shared memory and semaphores (IPC), the view of the cgroup tree (cgroup) and two clocks (time).

Common misunderstanding: "Inside a container /sys/fs/cgroup shows the host's whole tree." With a cgroup namespace (Docker's default on cgroup v2, --cgroupns=private) it starts at the container's own cgroup: /proc/self/cgroup reads 0::/. Without it, the container sees the full host path, which leaks host layout and confuses libraries that read limits.

Definition: UTS isolates "Hostname and NIS domain name"; IPC isolates "System V IPC, POSIX message queues"; cgroup_namespaces(7): "Cgroup namespaces virtualize the view of a process's cgroups", and "Each cgroup namespace has its own set of cgroup root directories"; time_namespaces(7) gives per-namespace offsets for CLOCK_MONOTONIC and CLOCK_BOOTTIME (wall-clock CLOCK_REALTIME is not namespaced), which matters when a container is checkpointed on one host and restored on another (CRIU).

text
Kubernetes pod with two containers
1  pause container creates the net, ipc and uts namespaces
2  app container joins them: same hostname (pod name), same SysV shared memory
3  sidecar joins them too: can attach to the app's POSIX shm segment
4  each container still has its own mnt and pid namespaces (unless shareProcessNamespace)

Real scenarios:

  • PostgreSQL in a container uses System V or POSIX shared memory; two containers sharing --ipc=container:pg can attach to it, separate IPC namespaces cannot.
  • hostname in a pod returns the pod name because the pod shares one UTS namespace.
  • Libraries that compute CPU limits from /proc/self/cgroup break when the container runs with --cgroupns=host and the path does not exist under the container's /sys/fs/cgroup mount; the Go package in this chapter falls back to the mount root.
  • CRIU live migration uses time namespaces so CLOCK_MONOTONIC does not jump backwards after restore.
NamespaceDocker defaultKubernetes
UTSPrivate (hostname = container ID unless --hostname)Per pod (pod name)
IPCPrivate, --ipc=shareable/host/container:<name>Per pod, hostIPC
CgroupPrivate on cgroup v2, host on v1 (--cgroupns)Private on cgroup v2
TimeNot used by defaultNot used

Fix: know these exist when a symptom involves the hostname, shared memory or a library misreading limits; nothing to configure in the common case.

unshare and nsenter Important ​

In plain words: unshare runs a command in new namespaces; nsenter runs a command inside the namespaces of an existing process. Together they are the "container toolkit" every Linux box already has (util-linux).

Common misunderstanding: "unshare --pid bash gives me PID 1." Not without --fork: unshare(2) with CLONE_NEWPID puts the caller's next child in the new PID namespace, so the man page's example is unshare --fork --pid --mount-proc readlink /proc/self, which prints 1. Without --mount-proc, ps still reads the host's /proc.

Definition: unshare(1) creates the namespaces given by --mount, --uts, --ipc, --net, --pid, --user, --cgroup, --time; --map-root-user maps the caller to root in a new user namespace; --kill-child kills the namespace's processes when unshare dies; --<type>=<file> makes a namespace persistent by bind-mounting it. nsenter(1) "executes program in the namespace(s) that are specified in the command-line options"; --target PID picks the process whose /proc/PID/ns/* to join, --all joins every namespace of it, and each --mount/--net/... flag joins one. lsns lists namespaces with their owning processes.

text
Debug a distroless container from the node (no shell, no tools inside)
1  pid=$(crictl inspect --output go-template --template '...pid...' <id>)   (Docker: docker inspect)
2  nsenter --target $pid --net ss -ltnp      host's ss, container's sockets
3  nsenter --target $pid --net tcpdump -ni eth0 port 8080
4  nsenter --target $pid --mount --pid ps -ef   only works if the image has ps
5  cat /proc/$pid/status | grep -E 'CapEff|Seccomp|NoNewPrivs'

Real scenarios:

  • Checking whether a pod can reach the database without installing tools in the image: nsenter --target <pid> --net curl ... from the node.
  • Reproducing "the app sees only one CPU" by running it under unshare plus a cgroup on a test box.
  • Testing hostname-dependent config with unshare --uts sh -c 'hostname prod-1; ./app'.
  • Writing a teaching or CI tool that builds a sandbox without a runtime (the Lab script).
ToolJoins or createsTypical use
unshareCreatesQuick sandboxes, tests, teaching
nsenterJoinsNode-side debugging of containers
ip netns execJoins a named netnsNetwork experiments, CNI debugging
docker exec / kubectl execJoins all namespaces + cgroup of the containerRun a command with the container's filesystem
kubectl debugNew container sharing the target's namespacesDistroless debugging without node access

Fix: prefer kubectl debug or docker exec for routine work; use nsenter when you need host binaries against a container's namespace or the container's own tools are missing.

cgroups v1 vs v2 Must-know ​

In plain words: A control group (cgroup) is a directory in a special filesystem. Processes are listed in it, limits are files you write, usage is files you read. Version 1 had one tree per resource; version 2 has one tree for everything.

Common misunderstanding: "cgroups are a Docker feature." They are a kernel feature used by systemd for every service on a modern distribution (systemctl status shows each unit's cgroup), by Kubernetes for pods and QoS classes, and by runc for containers. Docker only asks runc (or systemd) to create one.

Definition: cgroups(7): "The initial release of the cgroups implementation was in Linux 2.6.24"; because controllers grew "largely uncoordinated", work on a new implementation began in 3.10 and "cgroups version 2 ... was eventually made official with the release of Linux 4.5." In v2 "all mounted controllers reside in a single unified hierarchy"; "'Internal' processes are not permitted. With the exception of the root cgroup, processes may reside only in leaf nodes" (the kernel docs call it the no internal process constraint); "Active cgroups must be specified via the files cgroup.controllers and cgroup.subtree_control"; and "The tasks file has been removed" (v2 uses cgroup.procs). runc's docs: "Yes [you are on v2] if /sys/fs/cgroup/cgroup.controllers is present"; Kubernetes: stat -fc %T /sys/fs/cgroup/ prints cgroup2fs. The cgroup driver is who writes the files: cgroupfs (the runtime writes them directly) or systemd (the runtime asks systemd over D-Bus to create a scope/slice). Kubernetes: "if you use cgroup v2, use the systemd cgroup driver instead of cgroupfs", and the kubelet and runtime must use the same one.

From a Pod spec to cgroup files to runtime settings/sys/fs/cgroup (root: no cpu.max, no memory.max)kubepods.slice (node allocatable)kubepods-burstable.slice (QoS class)kubepods-burstable-pod<uid>.slicecri-containerd-<id>.scopecpu.max 200000 100000cpu.weight from requests.cpumemory.max 536870912Pod specrequests: cpu 500m, memory 256Mi (scheduling)limits: cpu 2, memory 512Mi (enforcement)Go serviceGOMAXPROCS: Go 1.25+ go.mod reads cpu.max (ceil,min 2); older go lines see all 64 node CPUsGOMEMLIMIT: never automatic, set ~90% of memory.maxphp-fpm (Laravel)nothing is automatic: pm.max_children x worker RSSmust fit under memory.max, or the kernel OOM-killsOver cpu.max: the group is throttled until the next 100 ms period (cpu.stat nr_throttled grows).Over memory.max after reclaim: OOM kill inside the group (memory.events oom_kill grows; Kubernetes: OOMKilled).
text
Same container limit, two layouts
v1 (one hierarchy per controller):
  /sys/fs/cgroup/cpu,cpuacct/docker/<id>/cpu.cfs_quota_us = 200000, cpu.cfs_period_us = 100000
  /sys/fs/cgroup/memory/docker/<id>/memory.limit_in_bytes = 536870912
  /sys/fs/cgroup/pids/docker/<id>/pids.max = 256
v2 (one unified tree, systemd driver):
  /sys/fs/cgroup/system.slice/docker-<id>.scope/cpu.max     = "200000 100000"
  /sys/fs/cgroup/system.slice/docker-<id>.scope/memory.max  = 536870912
  /sys/fs/cgroup/system.slice/docker-<id>.scope/pids.max    = 256

Real scenarios:

  • A Java 8 or Go library from 2019 reads /sys/fs/cgroup/memory/memory.limit_in_bytes, finds nothing on a cgroup v2 node and assumes "no limit"; the service is OOM-killed under load.
  • Upgrading nodes from Ubuntu 20.04 (v1) to 22.04 (v2) changes every monitoring query that read v1 file names (memory.usage_in_bytes becomes memory.current).
  • A kubelet configured with cgroupfs and containerd with SystemdCgroup = true fight over the tree: pods start but resource accounting is wrong or the kubelet refuses to start.
  • Kubernetes v1.35+: "Kubelet will no longer start on a cgroup v1 node by default" (failCgroupV1).
Productcgroup v2 status
LinuxOfficial since 4.5; runc recommends 5.2+ (freezer), 4.15 minimum
systemdUnified hierarchy default on current distributions; delegation of controllers to users (often only memory pids by default)
runc"fully supports cgroup v2 (unified mode) since v1.0.0-rc93"; systemd driver "highly recommended"
containerd / CRI-Ov2 since containerd v1.4 and CRI-O v1.20 (Kubernetes docs); SystemdCgroup = true
Kubernetesv2 stable since v1.25; needs kernel 5.8+; v1 deprecated in v1.35
DockerSupports both; docker info shows Cgroup Version and Cgroup Driver
Distributionsv2 by default: Fedora 31+, Debian 11+, Ubuntu 21.10+, RHEL 9+

Fix: run cgroup v2 with the systemd driver everywhere (kubelet and runtime), and make every library that reads limits v2-aware (Go 1.25+ is; the snippet below handles both).

Controllers, limits, OOM and resource accounting: cpu memory io pids Must-know ​

In plain words: Each controller owns one resource. cpu limits and weights CPU time, memory caps RAM and kills when the cap cannot be held, io throttles block devices, pids caps the number of tasks. Every controller also counts what the group used.

Common misunderstanding: "A CPU limit of 2 means the container may use 2 cores." It means 200 ms of CPU time per 100 ms period, spent on any number of cores. A Go service with 64 threads can burn the whole quota in the first 3 ms of a period and then sit throttled for the remaining 97 ms. The Go blog: "Throttling is a blunt mechanism ... it completely pauses application execution for the remainder of the throttling period."

Definition (cgroup-v2.rst):

  • cpu.max: "The maximum bandwidth limit", format $MAX $PERIOD, default "max 100000", "'max' for $MAX indicates no limit". cpu.weight: proportional share under contention, default "100", range [1, 10000]. cpu.stat reports usage_usec, user_usec, system_usec and, with the controller enabled, nr_periods, nr_throttled, throttled_usec.
  • memory.max: "Memory usage hard limit ... If a cgroup's memory usage reaches this limit and can't be reduced, the OOM killer is invoked in the cgroup." memory.high: "Memory usage throttle limit ... Going over the high limit never invokes the OOM killer". memory.oom.group: "all tasks belonging to the cgroup ... are killed together or not at all". memory.events: counters low, high, max, oom, oom_kill, oom_group_kill. memory.current, memory.peak, memory.swap.max, memory.min/memory.low (protection).
  • io.max: "BPS and IOPS based IO limit", lines keyed by $MAJ:$MIN with rbps, wbps, riops, wiops.
  • pids.max: "Hard limit of number of processes", default "max"; pids.current, pids.events (max = times the limit was hit).
  • PSI (pressure stall information): cpu.pressure, memory.pressure, io.pressure per cgroup, lines some avg10=... avg60=... avg300=... total=... and full ...: the share of time some or all tasks were stalled on that resource.
text
Go service, cpu.max = "200000 100000" (2 CPUs), GOMAXPROCS = 64 (node size, go 1.24 module)
T+0 ms    GC + 40 request goroutines run on 64 threads in parallel
T+3 ms    group has used 200 ms of CPU time -> throttled (nr_throttled++)
T+3..100  every thread of the service paused; requests queue, p99 jumps by ~97 ms
T+100 ms  new period, quota refilled, burst repeats
Same service, GOMAXPROCS = 2: at most 2 threads run Go code, quota spread across the period
text
php-fpm pod, memory.max = 512Mi, pm.max_children = 20, worker RSS ~45 MiB under load
1  traffic spike: 20 workers busy -> 20 x 45 MiB + master + OPcache shm ~ 980 MiB wanted
2  memory.current reaches memory.max -> kernel reclaims page cache, then cannot free more
3  memory.events: max++ then oom++ -> OOM killer picks a victim inside the cgroup
4  victim = php-fpm master or the busiest worker; if PID 1 dies the container exits (code 137)
5  Kubernetes: lastState.terminated.reason = OOMKilled, restartCount++

Real scenarios:

  • p99 latency spikes every few seconds on an otherwise idle-looking service: cpu.stat shows nr_throttled climbing; fix GOMAXPROCS or raise/remove the limit.
  • A queue worker leaks memory slowly and is OOM-killed every few hours; memory.events oom_kill and the pod's OOMKilled reason confirm it.
  • A container with pids.max = 256 gets EAGAIN from fork (fork(2): "the PID limit (pids.max) imposed by the cgroup ... (PIDs) controller was reached") because a library spawns a process per request.
  • A noisy batch job saturates the node's disk; io.max on its cgroup (or io.weight) protects the database container's latency.
  • PSI memory.pressure some avg10 rising above a few percent warns of reclaim stalls before any OOM happens.
ProductHow limits are expressed
Docker--cpus, --cpu-shares (weight), --memory, --memory-reservation, --memory-swap, --pids-limit, --device-write-bps; --cpus="1.5" = --cpu-period=100000 --cpu-quota=150000
Composedeploy.resources.limits (cpus, memory, pids) and reservations
Kubernetesresources.limits (cpu -> cpu.max, memory -> memory.max), requests (cpu -> cpu.weight, scheduling); MemoryQoS uses memory.high
OCI config.jsonlinux.resources.cpu.quota/period/shares, memory.limit, pids.limit, blockIO, and unified for any v2 file
systemdCPUQuota=, MemoryMax=, MemoryHigh=, TasksMax=, IOReadBandwidthMax= on units and slices

Fix: read the accounting files before changing anything (cpu.stat, memory.events, memory.peak, PSI); set memory limits from measured peak plus headroom; for CPU, either set a limit and make the runtime match it (GOMAXPROCS, worker counts) or set only a request. Kubernetes-side sizing (QoS classes, quotas, VPA) is in Resources, Scheduling & Autoscaling; OOMKilled triage is in Kubernetes Observability & Troubleshooting.

OverlayFS: lowerdir, upperdir, workdir, copy-up, whiteouts Must-know ​

In plain words: OverlayFS stacks directories. Several read-only ones (the image layers) sit at the bottom, one writable directory (the container layer) sits on top, and the process sees the merge. Writing to a file from a lower layer first copies the whole file up; deleting it leaves a marker that hides it.

Common misunderstanding: "The container writes into the image." Lower directories are never modified: "The lower filesystem does not need to be writable" and every change lands in the upper directory. That is why one image can back a thousand containers, and why the container layer is a bad place for a database (whole-file copy-up, lost on removal).

Definition (Documentation/filesystems/overlayfs.rst): the mount is mount -t overlay overlay -olowerdir=/lower,upperdir=/upper,workdir=/work /merged; "The 'workdir' needs to be a directory on the same filesystem as upperdir" (it is the staging area for atomic copy-up and whiteout creation). Several lower layers are a colon list, "stacked beginning from the rightmost one and going left", so in lowerdir=/lower1:/lower2:/lower3 "lower1 will be the top"; without upperdir and workdir "the overlay will be read-only". Copy-up: when a lower file "is accessed in a way that requires write-access ... the file is first copied from the lower filesystem to the upper filesystem (copy_up)"; the process creates the directory chain, copies metadata, "then if the object is a file, the data is copied", then the xattrs; afterwards the upper copy is used directly. Whiteouts: "A whiteout is created as a character device with 0/0 device number or as a zero-size regular file with the xattr 'trusted.overlay.whiteout'"; an opaque directory ("trusted.overlay.opaque" set to "y") hides the whole lower directory of the same name. In image tarballs the OCI layer format encodes the same ideas as files: a whiteout is a name "prefixed with .wh." and "An opaque whiteout entry is a file with the name .wh..wh..opq"; the snapshotter converts them when it unpacks a layer.

mount -t overlay overlay -o lowerdir=L1:L2,upperdir=U,workdir=W mergedmerged/ app.txt config.yml (v2)names merged per directory; base.txt hidden by the whiteoutupperdir U (read-write, the container layer)config.yml (copied up, then written: v2)base.txt c--------- 0,0 (whiteout = char device 0/0)lowerdir L1 (top, read-only) app.txtlowerdir L2 (bottom, read-only) base.txt config.yml (v1)workdir W: empty dir, same filesystem as Ustaging area for copy-up and whiteout creationwrite to a lower file1 open(O_WRONLY) on merged/config.yml2 create parent dirs in U if missing3 copy metadata, then ALL data, xattrs4 later I/O goes straight to U's copyL2 is never modifieddelete a lower file or dirrm: whiteout entry in U hides the namerm -r + mkdir: opaque dir in U(trusted.overlay.opaque = y)in an image tarball (OCI layer)whiteout = file named .wh.base.txtopaque dir = .wh..wh..opq inside itthe snapshotter converts on unpackLookups: upper first, then each lower, top to bottom;no upperdir/workdir given = a read-only overlay.
text
echo v2 > /app/config.yml in a container (file exists only in an image layer)
1  open("/app/config.yml", O_WRONLY|O_TRUNC) on the merged view
2  overlay: object is in a lowerdir -> copy_up begins in workdir
3  create /app in upperdir if missing, copy owner/mode/mtime, copy data, copy xattrs
4  rename the finished copy into upperdir (atomic thanks to workdir on the same fs)
5  the write goes to upperdir/app/config.yml; lower layer still has v1
rm /app/old.log: upperdir gets a 0/0 char device "old.log"; merged no longer lists it

Real scenarios:

  • A container writes 2 GB into a file that came with the image: the first write copies all 2 GB into the upper layer, a latency spike and a disk-usage surprise.
  • docker diff and podman diff list exactly the upperdir: A (added), C (changed), D (deleted = whiteout).
  • Rootless Podman on older kernels used fuse-overlayfs; user_namespaces(7) lists "overlayfs (since Linux 5.11)" among filesystems mountable inside a user namespace, so native overlay works rootless on newer kernels.
  • Running Docker inside a container whose root is itself an overlay (docker:dind) needs a volume for /var/lib/docker, because stacking overlay on overlay is restricted.
ProductOverlay usage
Docker overlay2 (classic store)/var/lib/docker/overlay2/<id>/{diff,merged,work}, shortened l/ links for lowerdir lists
Docker 29+ containerd image store, containerd, nerdctloverlayfs snapshotter, one snapshot per layer, upper for the container
Kubernetes (containerd, CRI-O)Same snapshotters; the container layer counts as pod ephemeral storage
Podman / Buildahcontainers/storage overlay driver (native or fuse-overlayfs rootless)
LXC / IncusUsually a full rootfs per container on ZFS/btrfs/LVM/dir; overlay is not the default

Fix: keep writes out of the container layer (volumes, tmpfs for scratch, stdout for logs), keep big mutable files out of images. How layers are built and why RUN rm does not shrink an image is the Images & Dockerfiles chapter's subject (the image layers link).

OCI specifications: runtime spec, config.json, image spec, distribution spec Must-know ​

In plain words: Three short standards make containers portable. The image spec says how an image is packed, the distribution spec says how registries serve it, and the runtime spec says how an unpacked image plus a config.json becomes a running process.

Common misunderstanding: "runc runs images." runc never sees an image or a registry. It runs a bundle: a directory with a root filesystem and a config.json. Turning an image into a bundle (pull, verify digests, unpack layers into a snapshot, generate the config from the image config plus your docker run flags) is containerd's or Podman's job.

Definition: The runtime spec "aims to specify the configuration, execution environment, and lifecycle of a container"; "A container's configuration is specified as the config.json". The Linux part (config-linux.md) defines linux.namespaces (types pid, network, mount, ipc, uts, user, cgroup, time, each optionally with a path to join), uidMappings/gidMappings, cgroupsPath, resources (memory.limit, cpu.shares/quota/period, pids.limit, blockIO ...), and unified: it "allows cgroup v2 parameters to be ... set and modified", where "Each key in the map refers to a file in the cgroup unified hierarchy" and "Configuration unknown to the runtime MUST still be written to the relevant file"; plus seccomp, maskedPaths, readonlyPaths. The lifecycle (runtime.md) has states creating, created ("the container process has neither exited nor executed the user-specified program"), running and stopped, operations state, create, start, kill, delete, and hooks in order prestart (deprecated), createRuntime, createContainer, startContainer, poststart, poststop. The image spec (index, manifest, config, layers) and the distribution spec (the /v2/ registry API) are covered byte by byte in Images & Dockerfiles; the OCI itself was "launched on June 22nd 2015 by Docker, CoreOS and other leaders in the container industry". Current runtime-spec release: v1.3.0.

json
{
  "ociVersion": "1.2.1",
  "process": {
    "terminal": false,
    "user": { "uid": 65532, "gid": 65532 },
    "args": ["/orders-api"],
    "env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "PORT=8080"],
    "cwd": "/",
    "capabilities": {
      "bounding": ["CAP_NET_BIND_SERVICE"],
      "effective": [],
      "permitted": []
    },
    "rlimits": [{ "type": "RLIMIT_NOFILE", "hard": 65536, "soft": 65536 }],
    "noNewPrivileges": true
  },
  "root": { "path": "rootfs", "readonly": true },
  "hostname": "orders-api",
  "mounts": [
    { "destination": "/proc", "type": "proc", "source": "proc" },
    { "destination": "/dev", "type": "tmpfs", "source": "tmpfs", "options": ["nosuid", "strictatime", "mode=755", "size=65536k"] },
    { "destination": "/sys/fs/cgroup", "type": "cgroup", "source": "cgroup", "options": ["nosuid", "noexec", "nodev", "relatime", "ro"] },
    { "destination": "/tmp", "type": "tmpfs", "source": "tmpfs", "options": ["nosuid", "nodev", "size=64m"] }
  ],
  "annotations": {
    "org.example.note": "Illustrative excerpt. The seccomp block is intentionally incomplete (it does not even allow execve) and would stop the process from starting; real bundles use the runtime's default profile."
  },
  "linux": {
    "namespaces": [
      { "type": "pid" },
      { "type": "network", "path": "/var/run/netns/orders-api" },
      { "type": "ipc" },
      { "type": "uts" },
      { "type": "mount" },
      { "type": "cgroup" },
      { "type": "user" }
    ],
    "uidMappings": [{ "containerID": 0, "hostID": 100000, "size": 65536 }],
    "gidMappings": [{ "containerID": 0, "hostID": 100000, "size": 65536 }],
    "cgroupsPath": "system.slice:orders:api",
    "resources": {
      "memory": { "limit": 536870912 },
      "cpu": { "quota": 250000, "period": 100000 },
      "pids": { "limit": 256 },
      "unified": { "memory.high": "483183820", "io.max": "259:0 rbps=52428800 wiops=2000" }
    },
    "seccomp": {
      "defaultAction": "SCMP_ACT_ERRNO",
      "architectures": ["SCMP_ARCH_X86_64", "SCMP_ARCH_AARCH64"],
      "syscalls": [
        { "names": ["read", "write", "openat", "close", "epoll_pwait", "futex", "exit_group"], "action": "SCMP_ACT_ALLOW" }
      ]
    },
    "maskedPaths": ["/proc/kcore", "/proc/keys", "/proc/timer_list", "/sys/firmware"],
    "readonlyPaths": ["/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger"]
  }
}

The excerpt is illustrative and says so in its annotations: its seccomp allowlist is deliberately tiny (it does not even allow execve), so as written the runtime would fail to start /orders-api; real bundles carry the engine's default profile, whose shape is covered in Container Security.

text
OCI lifecycle, as runc implements it (runtime.md steps)
1  runc create demo   -> environment built from config.json: namespaces, cgroup, mounts, rootfs
2                       state: created (runc init waits; the user program has NOT run)
3  hooks: createRuntime (runtime ns), createContainer (container ns)
4  runc start demo    -> startContainer hook, then execve(process.args) -> state: running
5  poststart hooks
6  process exits (or runc kill demo TERM) -> state: stopped
7  runc delete demo   -> cgroup and state removed, poststop hooks run

Real scenarios:

  • NVIDIA's container toolkit and some CNI setups used OCI hooks (createRuntime) to inject devices or networking before the process starts.
  • Swapping runc for crun or runsc is a one-line runtime setting because all of them take the same bundle.
  • Debugging "what exactly did Docker ask for?": the generated bundle's config.json (under containerd's state directory for the task) shows every namespace, mount and cgroup value.
  • A Kubernetes RuntimeClass points the same pod spec at a different OCI runtime without changing the image.
ImplementationConsumes
runc, crun, youkiRuntime spec bundles (reference and alternative engines)
runsc (gVisor), kata-runtimeRuntime spec bundles, executed on a user-space kernel or in a VM
containerd, CRI-O, PodmanImage spec + distribution spec in, runtime spec bundle out
Registries (Docker Hub, GHCR, ECR, Harbor)Distribution spec
BuildKit, Buildah, kanikoProduce image-spec artefacts

Fix: when a container behaves oddly, read its effective config.json (or docker inspect / crictl inspect, which show the same fields) before guessing; when building tools, emit standard bundles and let any OCI runtime run them.

Low-level runtimes: runc, crun, youki Important ​

In plain words: The low-level (OCI) runtime is the small program that does the actual syscalls: create namespaces, write cgroup files, mount the rootfs, drop privileges, exec the process. It then exits; it is not a daemon.

Common misunderstanding: "runc is running while my container runs." runc run stays only in the foreground convenience mode; under containerd, runc create/start return as soon as the process is started, and the shim becomes its parent.

Definition: runc: "a CLI tool for spawning and running containers on Linux according to the OCI specification", the reference implementation that came out of Docker's libcontainer. crun is written in C: "runc ... re-execs itself and use a module written in C for setting up the environment before the container process starts", and crun "is faster than runc and has a much lower memory footprint" (its README benchmarks 100 sequential /bin/true containers). youki is "an implementation of the OCI runtime-spec in Rust, similar to runc", motivated by the system-call handling that is "tricky" in Go (namespaces, fork). Docker's docs name youki as "a runtime that can function as a runc drop-in replacement".

text
runc run demo (foreground, from the runc README)
1  runc (Go) parses config.json, prepares a socket pair
2  re-exec /proc/self/exe "init" with the C nsexec part: clone() into new namespaces
3  parent writes cgroup files and uid/gid maps; child sets up mounts, pivot_root
4  child applies capabilities, no_new_privs, seccomp, then waits on a fifo ("created")
5  start: child execve("/bin/sh") -> it IS the container process now

Real scenarios:

  • Fedora/RHEL Podman installs default to crun; Docker and most Kubernetes distributions default to runc.
  • High pod-churn platforms (CI, serverless) shave start-up latency with crun.
  • A vulnerability in runc affects every engine built on it, which is one reason sandboxes add a second boundary.
  • WebAssembly support in crun (crun built with WasmEdge/wasmtime) runs Wasm modules as "containers" through the same interface.
RuntimeLanguageDefault inNotes
runcGo (+ C nsexec)Docker, containerd, most KubernetesReference implementation; rootless and cgroup v2 support
crunCPodman on Fedora/RHEL, CRI-O on some distrosSmaller, faster start; usable as a library
youkiRustnone by defaultDrop-in replacement via containerd's runc shim (BinaryName)
runscGoopt-ingVisor's OCI runtime
kata-runtimeGo/Rustopt-inStarts a VM per pod; ships its own shim io.containerd.kata.v2

Fix: stay on the distribution's default unless you measured a reason; swap with BinaryName in containerd's runc options or Docker's runtimes in daemon.json, and keep runc/crun patched (they are on the escape path).

containerd, the shim and the CRI Must-know ​

In plain words: containerd is the daemon that owns images and containers on a node; a shim is a tiny per-container process that keeps the container alive and reports its exit; the CRI is the gRPC API the kubelet uses to ask any runtime (containerd, CRI-O) for pods and containers.

Common misunderstanding: "Kubernetes runs Docker." The kubelet speaks only the CRI; the Kubernetes v1.24 release "actually removed the dockershim". Images built with Docker still run, because they are OCI images and containerd or CRI-O runs them.

Definition: containerd "is an industry-standard container runtime with an emphasis on simplicity, robustness, and portability ... which can manage the complete container lifecycle of its host system: image transfer and storage, container execution and supervision, low-level storage and network attachments". Its runtime v2 API makes the shim a first-class plugin: "The runtime shim is what actually is invoked by containerd"; it "listens on the socket for ttRPC commands from containerd, and then invokes a separate program, the runtime engine, via fork/exec", for example "the io.containerd.runc.v2 shim invokes an OCI compliant runtime engine such as runc" (binary containerd-shim-runc-v2). Runtimes "that implement their own containerd shims include" Wasmtime, gVisor and Kata (Docker docs). The CRI "is a plugin interface which enables the kubelet to use a wide variety of container runtimes, without having a need to recompile the cluster components" and defines "the main gRPC protocol for the communication between the node components kubelet and container runtime"; "For Kubernetes v1.26 and later, the kubelet requires that the container runtime supports the v1 CRI API." containerd 2.x configures it under plugins.'io.containerd.cri.v1.runtime' in config version = 3.

Who starts the process: three stacks, one OCI runtime underneathDocker EngineKubernetes nodePodman (no daemon)docker CLIdockerd (API, networks)containerd (namespace moby)REST on docker.sockgRPCkubeletCRI (gRPC, unix socket)containerd CRI plugin or CRI-Opodman CLI (fork/exec)no daemonshim per container: containerd-shim-runc-v2 (ttRPC to containerd)conmon per containerOCI runtime: runc (Go) / crun (C) / youki (Rust) / runsc (gVisor) / kata-runtimereads config.json + rootfs (the bundle), sets up namespaces, cgroup, mounts, then execs and EXITScontainer process (PID 1 in its PID namespace)After start the shim (or conmon) is the parent: it holds stdio and reaps the exit code,so dockerd or containerd can restart without killing the containers.
toml
# /etc/containerd/config.toml (containerd 2.x, config version 3), CRI section only.
version = 3

[plugins.'io.containerd.cri.v1.runtime'.containerd]
  default_runtime_name = 'runc'

# runc through the runc v2 shim, cgroups managed by systemd (same driver as the kubelet).
[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.runc]
  runtime_type = 'io.containerd.runc.v2'
  [plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.runc.options]
    SystemdCgroup = true
    # BinaryName = '/usr/bin/crun'     # drop-in OCI runtime replacing runc

# gVisor: its own shim, selected by RuntimeClass handler "runsc".
[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.runsc]
  runtime_type = 'io.containerd.runsc.v1'

# Kata Containers: each pod in a lightweight VM.
[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.kata]
  runtime_type = 'io.containerd.kata.v2'

# WebAssembly via runwasi's Wasmtime shim.
[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.wasmtime]
  runtime_type = 'io.containerd.wasmtime.v1'
text
kubelet creates a pod with two containers (CRI calls)
1  RunPodSandbox  -> containerd: pause container, netns created, CNI plugin attaches eth0
2  PullImage x2   -> content store + snapshotter (overlayfs) unpack layers
3  CreateContainer(app) -> bundle generated, shim started, runc create
4  StartContainer(app)  -> runc start; runc exits; shim is the parent
5  same for the sidecar, joining the sandbox's net/ipc/uts namespaces
6  containerd restarts for an upgrade -> shims keep the containers running, reconnect later

Real scenarios:

  • systemctl restart containerd during a node upgrade does not kill pods, because the shims (not containerd) are the containers' parents.
  • crictl ps, crictl logs, crictl inspect on a node talk CRI to whatever runtime is installed; ctr talks containerd's own API and sees namespaces k8s.io (Kubernetes) and moby (Docker).
  • A cluster adds gVisor by installing runsc + its shim, adding a runtime section to containerd's config and a RuntimeClass with handler: runsc.
  • A default_runtime_name typo or a mismatched cgroup driver shows up as pods stuck in ContainerCreating with CRI errors in kubelet logs.
ComponentRole
containerdDaemon: content store, snapshotters, metadata, tasks; CRI plugin built in; CNCF graduated
CRI-OKubernetes-only CRI implementation (Red Hat/OpenShift), uses conmon + runc/crun
containerd-shim-runc-v2One per container (or pod); ttRPC server, holds stdio, reaps exit status
ctr / nerdctlcontainerd's debug CLI / Docker-compatible CLI for containerd
crictlCRI debug CLI for any runtime
kubeletCRI client; picks a runtime handler from RuntimeClass

Fix: on Kubernetes nodes, debug with crictl and journalctl -u containerd, keep the kubelet and runtime on the same cgroup driver (systemd), and pin containerd to a supported release (2.0 and 2.3 are LTS per containerd's release table). Node-level setup is in Kubernetes Architecture & Setup.

Docker Engine architecture (dockerd, containerd, runc) and Podman daemonless Must-know ​

In plain words: Docker is a client and a daemon: docker talks to dockerd, which delegates container execution to containerd, which starts a shim, which calls runc. Podman does the same job without a resident daemon: each podman command forks the runtime directly and leaves a small monitor (conmon) per container.

Common misunderstanding: "If dockerd crashes, all containers die." With --live-restore they keep running, and even without it the process tree belongs to the shim, not to dockerd. Conversely, "Podman has no daemon, so nothing supervises containers": conmon supervises each one, and restart policies come from systemd units (podman generate systemd, Quadlet) instead of a daemon.

Definition: Docker Engine "acts as a client-server application with: A server with a long-running daemon process dockerd", "APIs which specify interfaces that programs can use to talk to and instruct the Docker daemon" and "A command line interface (CLI) client docker". "Docker Engine uses containerd for managing the container lifecycle, which includes creating, starting, and stopping containers. By default, containerd uses runc as its container runtime." dockerd connects to containerd with --containerd and uses the containerd namespace moby by default. Podman: "a daemonless, open source, Linux native tool"; "Most users can simply alias Docker to Podman (alias docker=podman) without any problems"; it "relies on an OCI compliant Container Runtime (runc, crun, runv, etc) to interface with the operating system"; it supports pods, rootless operation and "a REST API providing both a Docker-compatible interface". "Conmon is a tool for monitoring OCI runtimes, used by both Podman and CRI-O."

text
docker run vs podman run, process tree afterwards
Docker:  systemd -> dockerd                         (API, networks, volumes, logs driver)
         systemd -> containerd                      (images, snapshots, tasks)
         containerd-shim-runc-v2 -> /orders-api     (runc ran and exited)
Podman:  podman run -> exits after start
         conmon -> /orders-api                      (crun or runc ran and exited)
         (rootless: everything owned by the user; pasta for networking)

Real scenarios:

  • A CI runner without a root daemon builds and runs containers with rootless Podman or Buildah; Docker-in-Docker would need --privileged.
  • docker compose against Podman's Docker-compatible socket (podman system service) lets teams keep Compose files while dropping dockerd.
  • A Docker daemon upgrade with live-restore enabled leaves production containers running on single-host deployments.
  • Kubernetes nodes need neither: containerd or CRI-O replaces both engines there.
EngineDaemonDefault OCI runtimeRootlessPodsCompose
Docker Enginedockerd + containerdruncRootless mode (opt-in)Nodocker compose
Podmannone (conmon per container)crun (Fedora/RHEL), runc elsewhereDefault for non-root usersYes, Kubernetes YAML in/outpodman compose or Docker's against the socket
nerdctlcontainerd onlyruncYes (RootlessKit)Nonerdctl compose
CRI-Ocrio (Kubernetes only)runc or crunYesKubernetes podsn/a

Fix: pick by environment: Docker Engine or Docker Desktop for the widest tooling on developer machines; Podman for rootless and daemonless hosts, systemd integration (Quadlet) and RHEL; containerd (or CRI-O) on Kubernetes nodes. docker run and Compose usage is in Running Containers.

LXC, LXD and Incus: system containers Good to know ​

In plain words: Application containers run one service per container. System containers run a whole Linux distribution with systemd as PID 1, SSH and cron, managed like a lightweight VM but sharing the host kernel.

Common misunderstanding: "LXC is old Docker." LXC is a separate, still-maintained project with a different goal: an environment "as close as possible to a standard Linux installation but without the need for a separate kernel". LXD and Incus build on it today.

Definition: LXC "is a userspace interface for the Linux kernel containment features ... it lets Linux users easily create and manage system or application containers", using "Kernel namespaces (ipc, uts, mount, pid, network and user)", "Apparmor and SELinux profiles", "Seccomp policies", "Chroots (using pivot_root)", "Kernel capabilities" and "CGroups"; "LXC containers are often considered as something in the middle between a chroot and a full fledged virtual machine." LXD (Canonical) is "a modern, secure and powerful system container and virtual machine manager"; Incus "was created by Aleksa Sarai as a community driven alternative to Canonical's LXD" and is "a next-generation system container, application container, and virtual machine manager". When running a system container, Incus "simulates a virtual version of a full operating system. To do this, it uses the functionality provided by the kernel running on the host system."

text
incus launch images:debian/13 web1   (LXD: lxc launch ubuntu:24.04 web1)
1  image is a full distro rootfs (not OCI layers) on ZFS/btrfs/LVM/dir storage
2  unprivileged container: user namespace maps root to a high host UID range
3  PID 1 = systemd; services, journald, sshd start as on a VM
4  incusbr0 bridge + veth gives it an IP; snapshots and live migration via the storage pool

Real scenarios:

  • A hosting provider packs dozens of customer "VPS" environments on one host as system containers.
  • A CI farm gives each job a fresh Ubuntu system container (systemd available) for integration tests that need services.
  • Developers run a Kubernetes-in-LXD lab because system containers boot in seconds and can run nested containers.
  • Legacy apps that expect cron, syslog and several daemons in one box move from VMs to system containers without a rewrite.
ToolContainer kindImagesManages VMs too
LXCSystem or applicationDistribution templatesNo
LXDSystem containersubuntu:, images: remotesYes (QEMU)
IncusSystem and application containersimages: remote; OCI images as application containersYes (QEMU)
Docker / PodmanApplication containersOCI imagesNo (Podman machine aside)

Fix: choose system containers when the unit you manage is "a machine" (SSH, systemd, many services); choose OCI application containers when the unit is "a service" that CI builds and an orchestrator schedules.

Sandboxes and microVMs: gVisor, Kata, Firecracker, and the container vs VM comparison Important ​

In plain words: A plain container's only wall is the kernel's syscall interface. A sandbox adds a second wall: gVisor answers the syscalls itself in a user-space kernel; Kata and Firecracker put each pod inside a small virtual machine with its own guest kernel.

Common misunderstanding: "Containers are a security boundary like VMs." gVisor's own README: "Containers are not a sandbox ... using a single, shared kernel allows for efficiency and performance gains, it also means that container escape is possible with a single vulnerability." The opposite mistake is "sandboxes are VMs, so they are slow to start": Firecracker states "< 125 ms startup time and a < 5 MiB memory footprint".

Definition: gVisor "is an application kernel that implements a Linux-like interface ... written in a memory-safe language (Go) and runs in userspace"; its OCI runtime "runsc ... integrates with Docker and Kubernetes". The Sentry "implements all the kernel functionality needed by the application, including: system calls, signal delivery, memory management and page faulting logic"; a Gofer "provides file system access". gVisor "is not a syscall filter (e.g. seccomp-bpf)" and "is also not a VM in the everyday sense". Kata Containers builds "a secure container runtime with lightweight virtual machines that feel and perform like containers, but provide stronger workload isolation using hardware virtualization technology as a second layer of defense"; the Kata runtime "launches the configured hypervisor" and a kata-agent in the guest creates the containers. Firecracker is "a virtual machine monitor (VMM) that uses the Linux Kernel Virtual Machine (KVM) to create and run microVMs" with "a minimalist design. It excludes unnecessary devices and guest-facing functionality to reduce the memory footprint and attack surface area"; it "was developed at Amazon Web Services to accelerate the speed and efficiency of services like AWS Lambda and AWS Fargate" and is integrated into Kata Containers.

Where the isolation boundary is (thicker line = stronger wall an escape must break)runc / crungVisor (runsc)Kata / Firecrackerclassic VMapp processapp processapp processapp + full guest OSSentry: user-spacekernel in Goguest kernel +kata-agentguest kernel,systemd, sshd ...VMM: Firecracker/QEMUhypervisorhost Linux kernel (KVM for the right two columns)boundary: namespaces,cgroups, caps, seccompstart: ms, overhead: ~0boundary: syscalls servedby the Sentry, few reach hostcost: syscall-heavy I/Oboundary: hardware virt.Firecracker: under 125 msboot, under 5 MiB per VMboundary: hardware virt.start: seconds to minutesoverhead: a whole OSAll four can be driven through the same OCI image and, on Kubernetes, the same Pod spec (RuntimeClass picks the handler).
yaml
# Map a RuntimeClass name to a CRI runtime handler configured in containerd.
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
  name: gvisor
handler: runsc            # [plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.runsc]
---
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
  name: kata
handler: kata
overhead:
  podFixed: { cpu: "250m", memory: "160Mi" }   # the guest kernel and VMM cost something
text
Multi-tenant build service, untrusted customer code, Kubernetes + RuntimeClass
1  pod spec: runtimeClassName: kata   (or gvisor)
2  kubelet -> CRI -> containerd picks runtime handler "kata" -> shim io.containerd.kata.v2
3  shim starts a VM (QEMU/Cloud Hypervisor/Firecracker) with a guest kernel + kata-agent
4  agent creates the container inside the guest with namespaces + cgroups as usual
5  a kernel exploit now compromises the guest kernel, not the node

Real scenarios:

  • AWS Lambda and Fargate run each function or task in a Firecracker microVM.
  • Managed Kubernetes offerings run selected pods under gVisor through a RuntimeClass for untrusted workloads.
  • Online code runners (playgrounds, notebooks, CI for forks) use gVisor or Kata so user code never shares the host kernel directly.
  • A database or anything syscall-heavy (lots of small I/O) can slow down noticeably under gVisor; benchmark before moving it.
Propertyrunc containergVisor (runsc)Kata / Firecracker microVMClassic VM
Kernel the app talks toHost kernelSentry (Go, user space)Guest kernelGuest kernel
Isolation boundaryNamespaces, cgroups, capabilities, seccompSentry + a small host syscall surfaceHardware virtualisation (KVM)Hardware virtualisation
Start-upMillisecondsMilliseconds to ~100 ms~100 ms class (Firecracker "< 125 ms")Seconds to minutes
Memory overhead~0Sentry per sandboxGuest kernel; Firecracker "< 5 MiB" VMMFull OS
CompatibilityFull Linux ABIMost syscalls, some gapsFull Linux ABI (guest)Anything, any OS
Image formatOCIOCIOCIDisk images
Kubernetes integrationDefaultRuntimeClassRuntimeClass (with overhead)KubeVirt

Fix: keep runc for trusted first-party services; add gVisor or Kata via RuntimeClass for untrusted or multi-tenant code; use microVMs (Firecracker) when you run functions or per-tenant sandboxes at high density; use full VMs for a different OS or kernel.

WebAssembly containers Good to know ​

In plain words: A Wasm module is a portable bytecode program that runs in a Wasm runtime (Wasmtime, WasmEdge, Spin) instead of as a native Linux binary. containerd can schedule it like a container by using a Wasm shim instead of runc.

Common misunderstanding: "Wasm replaces Linux containers." It replaces the process, not the orchestration: images still travel as OCI artefacts, Kubernetes still schedules pods, but inside the "container" there is no Linux userland, only a module with WASI capabilities.

Definition: runwasi is "a project to facilitate running wasm workloads managed by containerd either directly (ie. through ctr) or as directed by Kubelet via the CRI plugin"; its demo runs ctr run --rm --runtime=io.containerd.wasmtime.v1 ghcr.io/containerd/runwasi/wasi-demo-app:latest testwasm. Docker lists Wasmtime among runtimes that ship their own containerd shim. Docker Desktop's own Wasm feature is now marked: "Wasm workloads are deprecated and will be removed in a future Docker Desktop release."

text
1  OCI artefact with a .wasm layer pushed to a registry
2  RuntimeClass handler "wasmtime" -> containerd shim io.containerd.wasmtime.v1
3  shim instantiates the module in Wasmtime (sandboxed linear memory, WASI imports)
4  no runc, no rootfs of a distribution; start-up in milliseconds, tiny images

Real scenarios:

  • Edge functions and plugin systems where start-up time and density matter more than full POSIX compatibility.
  • Spin apps run on Kubernetes through the containerd-shim-spin shim that runwasi's README links.
  • Mixed nodes run normal containers and Wasm pods side by side, chosen per pod by RuntimeClass.
  • Workloads that need arbitrary syscalls, threads with full POSIX semantics or native libraries are not candidates yet.
OptionRuntimeStatus
runwasi shimsWasmtime, WasmEdgecontainerd project; CRI-compatible
containerd-shim-spinSpinLinked from runwasi
crun with Wasm handlerWasmEdge / wasmtimePodman/CRI-O path
Docker Desktop Wasm(various)Deprecated

Fix: treat Wasm as another runtime handler: same registry, same scheduler, different shim; evaluate WASI support for your language before committing.

Capabilities and seccomp (the privilege link) Important ​

In plain words: Even as UID 0, a container process holds only a subset of root's powers (capabilities) and may only make allowed system calls (seccomp). These are the last line between a compromised app and the shared kernel.

Common misunderstanding: "--privileged just gives a few extra permissions." It gives all capabilities, disables seccomp and AppArmor confinement and exposes host devices: effectively the container's root is the host's root.

Definition: capabilities(7) splits root's privileges into units such as CAP_NET_BIND_SERVICE, CAP_SYS_ADMIN, CAP_NET_ADMIN; runtimes start containers with a short default list and the OCI process.capabilities sets (bounding, effective, permitted, inheritable, ambient) say which remain. seccomp(2) attaches a BPF filter to the process; Docker's default profile "disables around 44 system calls out of 300+" and works as an allowlist. noNewPrivileges stops setuid binaries from gaining privileges. Profiles, cap_drop: ALL, RuntimeDefault seccomp, AppArmor/SELinux and admission policies are taught in Container Security.

text
Attacker gets a shell in a runc container (root, default Docker profile)
1  tries mount -t proc ... on the host path        -> EPERM (no CAP_SYS_ADMIN)
2  tries kexec_load / init_module                    -> blocked by seccomp + no CAP_SYS_MODULE
3  tries an unpatched kernel bug through an allowed syscall -> this is where gVisor/Kata help

Real scenarios:

  • Binding port 80 as non-root needs CAP_NET_BIND_SERVICE (or a higher port).
  • A debugging tool (strace) inside a container fails with EPERM until SYS_PTRACE is added (prefer kubectl debug with a profile).
  • Container escape CVEs often require CAP_SYS_ADMIN or a missing seccomp filter; defaults stop many of them.
  • --privileged Docker-in-Docker on shared CI runners is a common, avoidable risk.
ProductDefault
Docker / PodmanReduced capability set, default seccomp profile, AppArmor/SELinux where present
KubernetesRuntime defaults; seccompProfile: RuntimeDefault and capabilities.drop: [ALL] are opt-in per pod (enforced by Pod Security "restricted")
gVisorSentry enforces its own syscall surface on top

Fix: drop all capabilities and add back only what is needed, keep the runtime's default seccomp profile, never use --privileged for apps.

Cgroup-aware runtimes: GOMAXPROCS, GOMEMLIMIT, PHP-FPM pm settings Must-know ​

In plain words: Language runtimes size themselves from what they think the machine has. Inside a container, "the machine" is the node, but the budget is the cgroup. Unless the runtime reads the cgroup files (or you tell it), it plans for 64 CPUs and 256 GB while the kernel enforces 2 CPUs and 512 MiB.

Common misunderstanding: "Go handles containers automatically now." Go 1.25 derives GOMAXPROCS from the CPU limit, but only when the main module's go.mod says go 1.25 or later: the GODEBUG defaults are "amended to match the Go version listed in go.mod", and the blog says "You can get the new defaults simply by setting the Go version to 1.25.0 or higher in your go.mod." No Go version derives GOMEMLIMIT from memory.max. PHP-FPM reads nothing: pm.max_children is whatever the pool file says.

Definition:

  • GOMAXPROCS "limits the number of operating system threads that can execute user-level Go code simultaneously" (runtime docs). Go 1.25 release notes: "On Linux, the runtime considers the CPU bandwidth limit of the cgroup containing the process, if any. If the CPU bandwidth limit is lower than the number of logical CPUs available, GOMAXPROCS will default to the lower limit"; "The Go runtime does not consider the 'CPU requests' option"; it "periodically updates GOMAXPROCS" when limits change; both behaviours are disabled by setting GOMAXPROCS or calling runtime.GOMAXPROCS, or with GODEBUG=containermaxprocs=0 / updatemaxprocs=0. The runtime source rounds: "A limit less than 2 is rounded up to 2, and any fractional component is rounded up" (ceil, then max(limit, 2)). uber-go/automaxprocs, the pre-1.25 library, rounds down by default ("It rounds the value down (floor)") with a minimum of 1 (maxprocs.Min).
  • GOMEMLIMIT "sets a soft memory limit for the runtime. This memory limit includes the Go heap and all other memory managed by the runtime, and excludes external memory sources such as mappings of the binary itself, memory managed in other languages"; added in Go 1.19; default math.MaxInt64 (off); settable at run time with runtime/debug.SetMemoryLimit. The GC guide: use it when "the Go program is the only program with access to some set of resources (i.e. some kind of memory reservation, like a container memory limit)", and "a good rule of thumb is to leave an additional 5-10% of headroom to account for memory sources the Go runtime is unaware of."
  • PHP-FPM pm settings (php.net): pm is static ("the number of child processes is fixed (pm.max_children)"), dynamic ("set dynamically based on ... pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers") or ondemand (spawned on request, "idle processes are killed after pm.process_idle_timeout"); pm.max_requests recycles workers; the stock www.conf ships pm = dynamic, pm.max_children = 5. Each worker is a process whose memory is charged to the container's cgroup.
text
The same 2-CPU / 512 MiB limit, three runtimes
Go, go.mod "go 1.24", 64-core node  -> GOMAXPROCS=64, GOMEMLIMIT=off  -> throttling, OOM under GC lag
Go, go.mod "go 1.25"                -> GOMAXPROCS=2 (from cpu.max),    GOMEMLIMIT still off
Go + cgroupres.Tune(10) or env vars -> GOMAXPROCS=2, GOMEMLIMIT=~460 MiB -> GC works harder before OOM
php-fpm pm=dynamic max_children=50  -> 50 x 45 MiB = 2.2 GiB possible -> OOMKilled at peak
php-fpm pm=static  max_children=8   -> 8 x 45 MiB + reserve < 512 MiB -> 503s queue instead of OOM

Real scenarios:

  • A Go API in Kubernetes with limits.cpu: 2 on 96-core nodes shows high p99 and nr_throttled growth until GOMAXPROCS is set (or the module moves to go 1.25).
  • A Go service with a 1 GiB limit and a heap that briefly doubles during GC is OOM-killed; GOMEMLIMIT at ~90 % of memory.max makes the GC run earlier instead.
  • A Laravel php-fpm container copied from a VM config (pm.max_children = 50) gets OOMKilled on the first traffic spike.
  • Laravel Octane: "By default, Octane will start an application request worker for each CPU core provided by your machine", which in a container is the node's core count, not the CPU limit; set --workers explicitly.
  • Queue workers: php artisan queue:work --memory=128 (Laravel's default limit: "By default, this limit is 128 megabytes") exits a worker before it outgrows its share of the container.
RuntimeReads cgroup limits by itself?What to set
Go 1.25+ (go.mod 1.25+)CPU limit -> GOMAXPROCS (ceil, min 2), updated periodically; memory: noGOMEMLIMIT ~90-95 % of memory.max
Go 1.5-1.24 or go.mod below 1.25NoGOMAXPROCS (env, automaxprocs, or code) and GOMEMLIMIT (1.19+)
PHP-FPMNopm = static or dynamic with pm.max_children from memory, pm.max_requests
Laravel Octane (Swoole/RoadRunner/FrankenPHP)No (uses CPU count)--workers, --max-requests
Laravel queue workersNo--memory, --max-jobs, --max-time, number of worker containers

Fix: make the runtime match the cgroup: the Go section shows a stdlib package that reads cpu.max/memory.max (v1 and v2) and sets both values, and the Laravel section sizes the FPM pool from memory.max at start-up.

Mechanics ​

What docker run does, syscall by syscall ​

text
docker run -d --name api --memory 512m --cpus 2 --pids-limit 256 -p 8080:8080 orders-api:1.4.2
1   docker CLI     POST /containers/create, /containers/{id}/start on /var/run/docker.sock
2   dockerd        resolves the image in containerd's content store (namespace moby), creates
                   the network endpoint (veth pair, docker0 port, iptables DNAT for 8080)
3   containerd     prepares an overlayfs snapshot: lowerdir = image layers, upperdir = new
4   containerd     writes the OCI bundle (rootfs mount + config.json), starts
                   containerd-shim-runc-v2 for this container
5   shim           runc create --bundle <dir> <id>
6   runc           clone(CLONE_NEWNS|NEWPID|NEWNET|NEWUTS|NEWIPC|NEWCGROUP) -> "runc init"
7   runc (parent)  systemd driver: StartTransientUnit docker-<id>.scope over D-Bus, then
                   cpu.max "200000 100000", memory.max 536870912, pids.max 256
8   runc init      mounts (overlay, proc, sysfs, tmpfs /dev, devpts, mqueue, cgroup2), pivot_root,
                   hostname, maskedPaths/readonlyPaths, capabilities, no_new_privs, seccomp
9   dockerd        moves the veth peer into the new netns as eth0, assigns 172.17.0.x
10  shim           runc start -> runc init execve()s /orders-api -> PID 1; runc exits
11  shim           keeps stdio pipes (log driver), waits for exit, reports status to containerd

Where each setting lands ​

You setKernel objectFile or syscallRead it back
--cpus 2 / limits.cpu: 2cgroup cpu controllercpu.max = 200000 100000cat /sys/fs/cgroup/.../cpu.max
--cpu-shares / requests.cpucgroup cpu weightcpu.weightcpu.weight
--memory 512m / limits.memorycgroup memorymemory.maxmemory.max, memory.events
--memory-reservation / MemoryQoScgroup memorymemory.low / memory.highsame
--pids-limitcgroup pidspids.maxpids.current, pids.events
--device-write-bpscgroup ioio.maxio.stat
--hostname, --uts=hostUTS namespacesethostname(2)hostname
--network, -pnet namespace, veth, iptablesip link, nft/iptables rulesnsenter --net ip addr
--userns-remap, rootless, hostUsers: falseuser namespaceuid_map, gid_mapcat /proc/<pid>/uid_map
--read-only, volumesmount namespacemount(2) flags, bind mounts/proc/<pid>/mountinfo
--cap-drop, --cap-addcapability setscapset(2)CapEff in /proc/<pid>/status
--security-opt seccomp=seccomp filterseccomp(2)Seccomp: 2 in /proc/<pid>/status
--initPID 1 = docker-init (tini)process treeps -o pid,cmd inside

Knobs ​

KnobWhereDefaultNotes
cpu.maxcgroup v2max 100000$MAX $PERIOD in microseconds
cpu.max.burstcgroup v20Lets a group bank unused quota for bursts
cpu.weightcgroup v2100Range 1-10000; Docker's --cpu-shares default 1024 maps onto it
memory.max / memory.highcgroup v2maxHard limit (OOM) / throttle limit (no OOM)
memory.oom.groupcgroup v201 = kill the whole group together
memory.swap.maxcgroup v2maxKubernetes sets swap off unless the node allows it
pids.maxcgroup v2maxDocker --pids-limit, kubelet --pod-max-pids / PodPidsLimit
user.max_*_namespaces/proc/sys/user/per-systemnamespaces(7): limits on namespaces per user
kernel.unprivileged_userns_clone / AppArmor userns restrictionssysctl (distribution-specific)variesSome distributions restrict unprivileged user namespaces
SystemdCgroupcontainerd config.tomlfalse in generated defaultsSet true with a systemd-driver kubelet
cgroupDriverkubelet configcgroupfssystemd on cgroup v2
failCgroupV1kubelet configtrue since v1.35Refuses to start on v1 nodes
GOMAXPROCSenv / runtime.GOMAXPROCSCPUs, or cgroup CPU limit with go.mod 1.25+Setting it disables the container-aware default
GODEBUG=containermaxprocs=0,updatemaxprocs=0env / //go:debug1 with go.mod 1.25+Opt out of the 1.25 behaviour
GOMEMLIMITenv / debug.SetMemoryLimitmath.MaxInt64 (off)Units B, KiB, MiB, GiB, TiB
pm, pm.max_children, pm.max_requestsphp-fpm pooldynamic, 5, 0 in stock www.confSize from memory, not from CPUs
--live-restoredockerdoffContainers survive daemon restarts

Error messages you will actually see ​

Message or symptomMeaningFix
Kubernetes Reason: OOMKilled, Exit Code: 137Memory over limits.memory; 137 = 128 + SIGKILLRaise the limit or cut usage; GOMEMLIMIT, smaller FPM pool
memory.events oom_kill > 0 with no restartA child (not PID 1) was killedSame; check which process with dmesg
nr_throttled growing in cpu.stat, p99 spikesCPU quota exhausted early in each periodGOMAXPROCS/worker count = limit, or no CPU limit
EAGAIN from fork/clonepids.max reached (fork(2)), often zombies piling upReap children (--init), raise pids.max
fork returns ENOMEM in a namespaceThe namespace's init died (pid_namespaces(7))Keep PID 1 alive; it must outlive its children
pivot_root: Invalid argument (EINVAL)"new_root is not a mount point" (or a shared propagation)Bind-mount the rootfs onto itself, --make-rprivate /
pivot_root: Device or resource busy (EBUSY)new_root or put_old on the current root mountUse a separate mount for the rootfs
unshare failed: Operation not permittedNo CAP_SYS_ADMIN, or unprivileged user namespaces disabled by the distributionRun as root, add --user --map-root-user, check sysctls/AppArmor
WARNING: No swap limit support (docker info)Kernel/cgroup without swap accountingExpected on some hosts; swap limits ignored
kubelet ... cgroup v1 ... refusing to startfailCgroupV1 default since v1.35Move the node to cgroup v2 (or set the flag false temporarily)
exec format errorBinary for another CPU architectureBuild the right platform (see Images & Dockerfiles)
operation not permitted from a syscall insideDropped capability or seccomp SCMP_ACT_ERRNOAdd the specific capability, or a custom profile, never --privileged

Go ​

The Go side of this chapter is a stdlib package that does what a container-aware runtime does: find the process's cgroup, read cpu.max and memory.max (or their v1 equivalents) on the cgroup and its ancestors, and turn them into GOMAXPROCS and GOMEMLIMIT. It matters because this KB's modules declare go 1.24 (the Go 1.25 default is therefore off, see Cgroup-aware runtimes) and because no Go version sets GOMEMLIMIT for you.

Before ​

A typical service main: correct code, but it trusts the runtime defaults inside a container (it builds, vets and runs as go/before):

go
// Command before is a typical service main: correct code that trusts the Go
// runtime defaults inside a container.
//
// go.mod says "go 1.24", so GODEBUG containermaxprocs=0 even when a newer
// toolchain builds it: GOMAXPROCS = runtime.NumCPU() = every CPU of the node,
// whatever cpu.max says. GOMEMLIMIT is off, so the GC paces only by GOGC=100
// and the heap may double before a cycle, past memory.max.
package main

import (
	"log"
	"net/http"
)

func routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	return mux
}

func main() {
	srv := &http.Server{Addr: ":8080", Handler: routes()}
	log.Fatal(srv.ListenAndServe())
}

After ​

The package (cgroupres): Read parses /proc/self/cgroup, detects v2 by cgroup.controllers, walks from the leaf cgroup up to the mount and keeps the smallest cpu.max and memory.max; Procs mirrors the Go 1.25 rounding (ceil, minimum 2, never above the CPU count); MemLimit keeps a headroom percentage; MakePlan never overrides an explicit GOMAXPROCS or GOMEMLIMIT environment variable.

go
// Package cgroupres reads the CPU and memory limits that the cgroup of the
// current process imposes, and turns them into GOMAXPROCS and GOMEMLIMIT
// values. It only uses the standard library and the files the kernel
// exposes under /proc and /sys/fs/cgroup, so it can be tested on any OS by
// pointing it at a fake root directory.
//
// Go 1.25+ already derives GOMAXPROCS from the cgroup CPU limit, but only
// when the main module's go.mod says go 1.25 or later (GODEBUG
// containermaxprocs). No Go version derives GOMEMLIMIT from memory.max.
package cgroupres

import (
	"bufio"
	"errors"
	"fmt"
	"io/fs"
	"math"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

// Limits is what the cgroup hierarchy allows this process.
type Limits struct {
	Version   int     // 2 (unified), 1 (legacy) or 0 when no cgroup was found
	Path      string  // cgroup path from /proc/self/cgroup, e.g. "/" or "/kubepods.slice/..."
	CPU       float64 // CPU bandwidth limit in CPUs (quota/period); 0 = no limit
	MemoryMax int64   // hard memory limit in bytes; 0 = no limit
}

// ErrNoCgroup means /proc/self/cgroup does not exist (not Linux, or no procfs).
var ErrNoCgroup = errors.New("cgroupres: no cgroup information found")

// v1Unlimited: cgroup v1 reports "no memory limit" as a huge page-aligned
// number (for example 9223372036854771712), not as "max".
const v1Unlimited = int64(1) << 60

// Read inspects root+"/proc/self/cgroup" and the cgroup filesystem mounted at
// root+"/sys/fs/cgroup". Production code passes root = "/".
func Read(root string) (Limits, error) {
	f, err := os.Open(filepath.Join(root, "proc/self/cgroup"))
	if errors.Is(err, fs.ErrNotExist) {
		return Limits{}, ErrNoCgroup
	}
	if err != nil {
		return Limits{}, err
	}
	defer f.Close()

	mount := filepath.Join(root, "sys/fs/cgroup")
	if _, err := os.Stat(filepath.Join(mount, "cgroup.controllers")); err == nil {
		// cgroup v2: one line "0::<path>".
		path, err := v2Path(f)
		if err != nil {
			return Limits{}, err
		}
		l := Limits{Version: 2, Path: path}
		for _, dir := range ancestors(mount, path) {
			if q, ok := readV2CPU(filepath.Join(dir, "cpu.max")); ok && (l.CPU == 0 || q < l.CPU) {
				l.CPU = q
			}
			if m, ok := readBytes(filepath.Join(dir, "memory.max")); ok && (l.MemoryMax == 0 || m < l.MemoryMax) {
				l.MemoryMax = m
			}
		}
		return l, nil
	}

	// cgroup v1: one line per hierarchy, "<id>:<controllers>:<path>".
	paths, err := v1Paths(f)
	if err != nil {
		return Limits{}, err
	}
	l := Limits{Version: 1, Path: paths["memory"]}
	for _, dir := range ancestors(v1Mount(mount, "cpu,cpuacct", "cpuacct,cpu", "cpu"), paths["cpu"]) {
		quota, okQ := readInt(filepath.Join(dir, "cpu.cfs_quota_us"))
		period, okP := readInt(filepath.Join(dir, "cpu.cfs_period_us"))
		if okQ && okP && quota > 0 && period > 0 {
			if q := float64(quota) / float64(period); l.CPU == 0 || q < l.CPU {
				l.CPU = q
			}
		}
	}
	for _, dir := range ancestors(filepath.Join(mount, "memory"), paths["memory"]) {
		if m, ok := readInt(filepath.Join(dir, "memory.limit_in_bytes")); ok && m > 0 && m < v1Unlimited &&
			(l.MemoryMax == 0 || m < l.MemoryMax) {
			l.MemoryMax = m
		}
	}
	return l, nil
}

// v1Mount returns the first existing v1 hierarchy directory among names.
// The cpu controller may be mounted alone (/sys/fs/cgroup/cpu) or co-mounted
// with cpuacct under either name order; distributions usually add symlinks,
// but a plain separate mount is valid too (cgroups(7)).
func v1Mount(mount string, names ...string) string {
	for _, n := range names {
		if fi, err := os.Stat(filepath.Join(mount, n)); err == nil && fi.IsDir() {
			return filepath.Join(mount, n)
		}
	}
	return filepath.Join(mount, names[len(names)-1])
}

// ancestors returns the cgroup directory for path and every parent up to the
// mount point. A limit on any ancestor also constrains this process. If the
// path is not visible (no cgroup namespace, cgroup bind-mounted at its own
// root) only the mount point itself is returned.
func ancestors(mount, path string) []string {
	dir := filepath.Join(mount, filepath.FromSlash(path))
	if _, err := os.Stat(dir); err != nil {
		return []string{mount}
	}
	var out []string
	for {
		out = append(out, dir)
		if dir == mount || len(dir) <= len(mount) {
			return out
		}
		dir = filepath.Dir(dir)
	}
}

func v2Path(f *os.File) (string, error) {
	s := bufio.NewScanner(f)
	for s.Scan() {
		if p, ok := strings.CutPrefix(s.Text(), "0::"); ok {
			return p, nil
		}
	}
	if err := s.Err(); err != nil {
		return "", err
	}
	return "", fmt.Errorf("cgroupres: no unified (0::) line in /proc/self/cgroup")
}

func v1Paths(f *os.File) (map[string]string, error) {
	out := map[string]string{}
	s := bufio.NewScanner(f)
	for s.Scan() {
		parts := strings.SplitN(s.Text(), ":", 3)
		if len(parts) != 3 {
			continue
		}
		for _, c := range strings.Split(parts[1], ",") {
			out[c] = parts[2]
		}
	}
	return out, s.Err()
}

// readV2CPU parses cpu.max: "$MAX $PERIOD", where $MAX may be "max".
func readV2CPU(name string) (float64, bool) {
	b, err := os.ReadFile(name)
	if err != nil {
		return 0, false
	}
	fields := strings.Fields(string(b))
	if len(fields) != 2 || fields[0] == "max" {
		return 0, false
	}
	quota, err1 := strconv.ParseFloat(fields[0], 64)
	period, err2 := strconv.ParseFloat(fields[1], 64)
	if err1 != nil || err2 != nil || quota <= 0 || period <= 0 {
		return 0, false
	}
	return quota / period, true
}

// readBytes parses memory.max: a byte count or "max".
func readBytes(name string) (int64, bool) {
	b, err := os.ReadFile(name)
	if err != nil {
		return 0, false
	}
	v := strings.TrimSpace(string(b))
	if v == "max" {
		return 0, false
	}
	n, err := strconv.ParseInt(v, 10, 64)
	return n, err == nil && n > 0
}

func readInt(name string) (int64, bool) {
	b, err := os.ReadFile(name)
	if err != nil {
		return 0, false
	}
	n, err := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64)
	return n, err == nil
}

// Procs mirrors the Go 1.25 runtime rule (runtime/cgroup_linux.go): round the
// CPU limit up, use at least 2, and never exceed the logical CPU count.
// cpu == 0 means "no limit" and returns ncpu.
func Procs(cpu float64, ncpu int) int {
	if cpu <= 0 {
		return ncpu
	}
	p := int(math.Max(math.Ceil(cpu), 2))
	return min(p, ncpu)
}

// MemLimit returns the soft limit for GOMEMLIMIT: memory.max minus a headroom
// percentage for memory the Go runtime does not manage (the GC guide suggests
// 5-10%). limit == 0 means "no limit" and returns 0.
func MemLimit(limit int64, headroomPercent int) int64 {
	if limit <= 0 {
		return 0
	}
	return limit / 100 * int64(100-headroomPercent)
}

// Plan is what Tune would change. Zero fields mean "leave the runtime alone".
type Plan struct {
	Procs    int
	MemLimit int64
	Reasons  []string
}

// MakePlan decides, without touching the runtime. Explicit GOMAXPROCS or
// GOMEMLIMIT environment variables always win.
func MakePlan(l Limits, ncpu, headroomPercent int, getenv func(string) string) Plan {
	var p Plan
	switch {
	case getenv("GOMAXPROCS") != "":
		p.Reasons = append(p.Reasons, "GOMAXPROCS set in the environment: keep it")
	case l.CPU == 0:
		p.Reasons = append(p.Reasons, "no CPU limit: keep the runtime default")
	default:
		p.Procs = Procs(l.CPU, ncpu)
		p.Reasons = append(p.Reasons, fmt.Sprintf("cpu limit %.2f CPUs -> GOMAXPROCS=%d", l.CPU, p.Procs))
	}
	switch {
	case getenv("GOMEMLIMIT") != "":
		p.Reasons = append(p.Reasons, "GOMEMLIMIT set in the environment: keep it")
	case l.MemoryMax == 0:
		p.Reasons = append(p.Reasons, "no memory limit: keep GOMEMLIMIT off")
	default:
		p.MemLimit = MemLimit(l.MemoryMax, headroomPercent)
		p.Reasons = append(p.Reasons, fmt.Sprintf("memory.max %d -> GOMEMLIMIT=%d (%d%% headroom)", l.MemoryMax, p.MemLimit, headroomPercent))
	}
	return p
}
go
package cgroupres

import (
	"os"
	"runtime"
	"runtime/debug"
)

// Apply sets GOMAXPROCS and the soft memory limit from a Plan.
func Apply(p Plan) {
	if p.Procs > 0 {
		runtime.GOMAXPROCS(p.Procs)
	}
	if p.MemLimit > 0 {
		debug.SetMemoryLimit(p.MemLimit)
	}
}

// Tune reads the limits of the current process and applies them. Call it
// first thing in main. It returns the plan so the caller can log it.
func Tune(headroomPercent int) (Limits, Plan, error) {
	l, err := Read("/")
	if err != nil {
		return l, Plan{Reasons: []string{err.Error()}}, err
	}
	p := MakePlan(l, runtime.NumCPU(), headroomPercent, os.Getenv)
	Apply(p)
	return l, p, nil
}

The tests use fixture trees (a pod with its own cgroup namespace, a host view where only the pod's parent slice has limits, a cgroup v1 container whose path is not visible) plus temporary directories for "unlimited" files, and restore the runtime settings after Apply:

go
package cgroupres

import (
	"errors"
	"os"
	"path/filepath"
	"runtime"
	"runtime/debug"
	"testing"
)

func TestReadFixtures(t *testing.T) {
	tests := []struct {
		root string
		want Limits
	}{
		// Container with its own cgroup namespace: cgroup files sit at the mount root.
		{"testdata/v2-pod", Limits{Version: 2, Path: "/", CPU: 2.5, MemoryMax: 512 << 20}},
		// Host view: the container scope has no limit, its pod parent does.
		{"testdata/v2-host-view", Limits{Version: 2, Path: "/kubepods.slice/pod-a.slice/cri-abc.scope", CPU: 0.5, MemoryMax: 1 << 30}},
		// cgroup v1, path not visible inside the container: fall back to the mount root.
		{"testdata/v1-docker", Limits{Version: 1, Path: "/docker/abc", CPU: 1.5, MemoryMax: 256 << 20}},
	}
	for _, tt := range tests {
		t.Run(tt.root, func(t *testing.T) {
			got, err := Read(tt.root)
			if err != nil {
				t.Fatal(err)
			}
			if got != tt.want {
				t.Fatalf("Read(%q) = %+v, want %+v", tt.root, got, tt.want)
			}
		})
	}
}

func TestReadNoCgroup(t *testing.T) {
	if _, err := Read(t.TempDir()); !errors.Is(err, ErrNoCgroup) {
		t.Fatalf("err = %v, want ErrNoCgroup", err)
	}
}

func TestReadV2Unlimited(t *testing.T) {
	root := t.TempDir()
	write(t, root, "proc/self/cgroup", "0::/\n")
	write(t, root, "sys/fs/cgroup/cgroup.controllers", "cpu memory pids\n")
	write(t, root, "sys/fs/cgroup/cpu.max", "max 100000\n")
	write(t, root, "sys/fs/cgroup/memory.max", "max\n")
	got, err := Read(root)
	if err != nil {
		t.Fatal(err)
	}
	if got.CPU != 0 || got.MemoryMax != 0 {
		t.Fatalf("unlimited cgroup read as %+v", got)
	}
}

func TestReadV1UnlimitedMemory(t *testing.T) {
	root := t.TempDir()
	write(t, root, "proc/self/cgroup", "4:cpu,cpuacct:/\n12:memory:/\n")
	write(t, root, "sys/fs/cgroup/cpu,cpuacct/cpu.cfs_quota_us", "-1\n")
	write(t, root, "sys/fs/cgroup/cpu,cpuacct/cpu.cfs_period_us", "100000\n")
	write(t, root, "sys/fs/cgroup/memory/memory.limit_in_bytes", "9223372036854771712\n")
	got, err := Read(root)
	if err != nil {
		t.Fatal(err)
	}
	if got.Version != 1 || got.CPU != 0 || got.MemoryMax != 0 {
		t.Fatalf("got %+v, want v1 with no limits", got)
	}
}

func TestReadV1SeparateCPUMount(t *testing.T) {
	root := t.TempDir()
	write(t, root, "proc/self/cgroup", "3:cpu:/\n4:cpuacct:/\n12:memory:/\n")
	write(t, root, "sys/fs/cgroup/cpu/cpu.cfs_quota_us", "200000\n")
	write(t, root, "sys/fs/cgroup/cpu/cpu.cfs_period_us", "100000\n")
	write(t, root, "sys/fs/cgroup/memory/memory.limit_in_bytes", "134217728\n")
	got, err := Read(root)
	if err != nil {
		t.Fatal(err)
	}
	if got.Version != 1 || got.CPU != 2 || got.MemoryMax != 128<<20 {
		t.Fatalf("got %+v, want v1 cpu=2 memory=128MiB", got)
	}
}

func TestProcs(t *testing.T) {
	tests := []struct {
		cpu  float64
		ncpu int
		want int
	}{
		{0, 16, 16},  // no limit: logical CPUs
		{0.5, 16, 2}, // below 2 rounds up to 2
		{2.5, 16, 3}, // fractional part rounds up
		{4, 16, 4},   // exact
		{8, 4, 4},    // never above the CPU count
		{0.25, 1, 1}, // one CPU machine stays at 1
		{12.01, 64, 13},
	}
	for _, tt := range tests {
		if got := Procs(tt.cpu, tt.ncpu); got != tt.want {
			t.Errorf("Procs(%v, %d) = %d, want %d", tt.cpu, tt.ncpu, got, tt.want)
		}
	}
}

func TestMemLimit(t *testing.T) {
	if got := MemLimit(0, 10); got != 0 {
		t.Fatalf("no limit -> %d, want 0", got)
	}
	if got, want := MemLimit(1<<30, 10), int64(1<<30)/100*90; got != want {
		t.Fatalf("MemLimit(1GiB, 10) = %d, want %d", got, want)
	}
}

func TestMakePlanRespectsEnvironment(t *testing.T) {
	l := Limits{Version: 2, CPU: 2.5, MemoryMax: 512 << 20}
	env := map[string]string{}
	getenv := func(k string) string { return env[k] }

	p := MakePlan(l, 16, 10, getenv)
	if p.Procs != 3 || p.MemLimit != MemLimit(512<<20, 10) {
		t.Fatalf("plan = %+v", p)
	}

	env["GOMAXPROCS"] = "8"
	env["GOMEMLIMIT"] = "400MiB"
	p = MakePlan(l, 16, 10, getenv)
	if p.Procs != 0 || p.MemLimit != 0 {
		t.Fatalf("explicit env must win, plan = %+v", p)
	}
	if len(p.Reasons) != 2 {
		t.Fatalf("reasons = %q", p.Reasons)
	}
}

func TestApplyRestores(t *testing.T) {
	oldProcs := runtime.GOMAXPROCS(0)
	oldLimit := debug.SetMemoryLimit(-1) // a negative value only reads the limit
	t.Cleanup(func() {
		runtime.GOMAXPROCS(oldProcs)
		debug.SetMemoryLimit(oldLimit)
	})
	Apply(Plan{Procs: 2, MemLimit: 256 << 20})
	if got := runtime.GOMAXPROCS(0); got != 2 {
		t.Fatalf("GOMAXPROCS = %d, want 2", got)
	}
	if got := debug.SetMemoryLimit(-1); got != 256<<20 {
		t.Fatalf("memory limit = %d, want %d", got, 256<<20)
	}
}

func write(t *testing.T, root, name, content string) {
	t.Helper()
	p := filepath.Join(root, name)
	if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
		t.Fatal(err)
	}
}

A CLI to inspect any root (real or fixture) and optionally apply the plan:

go
// Command tune prints, and optionally applies, the GOMAXPROCS and GOMEMLIMIT
// values that follow from the cgroup limits of this process. In a service you
// would call cgroupres.Tune(10) as the first line of main instead.
//
//	go run ./cmd/tune                                    # real /proc and /sys
//	go run ./cmd/tune -root cgroupres/testdata/v2-pod    # a fixture
package main

import (
	"errors"
	"flag"
	"fmt"
	"os"
	"runtime"
	"runtime/debug"

	"academy/containers-under-the-hood/cgroupres"
)

func main() {
	root := flag.String("root", "/", "directory that holds proc/ and sys/fs/cgroup/")
	headroom := flag.Int("headroom", 10, "percent of memory.max kept outside GOMEMLIMIT")
	apply := flag.Bool("apply", false, "apply the plan to this process")
	flag.Parse()

	fmt.Printf("before: GOMAXPROCS=%d NumCPU=%d GOMEMLIMIT=%d\n",
		runtime.GOMAXPROCS(0), runtime.NumCPU(), debug.SetMemoryLimit(-1))

	l, err := cgroupres.Read(*root)
	switch {
	case errors.Is(err, cgroupres.ErrNoCgroup):
		fmt.Println("no cgroup found (not Linux?): leaving the runtime defaults alone")
		return
	case err != nil:
		fmt.Fprintln(os.Stderr, "tune:", err)
		os.Exit(1)
	}
	fmt.Printf("cgroup v%d path=%s cpu=%.2f memory.max=%d\n", l.Version, l.Path, l.CPU, l.MemoryMax)

	p := cgroupres.MakePlan(l, runtime.NumCPU(), *headroom, os.Getenv)
	for _, r := range p.Reasons {
		fmt.Println("plan:", r)
	}
	if *apply {
		cgroupres.Apply(p)
		fmt.Printf("after: GOMAXPROCS=%d GOMEMLIMIT=%d\n", runtime.GOMAXPROCS(0), debug.SetMemoryLimit(-1))
	}
}
text
module academy/containers-under-the-hood

go 1.24

The Kubernetes side: limits become cgroup files; the downward API passes the CPU limit as GOMAXPROCS (the package keeps an explicit env value), while GOMEMLIMIT is left to cgroupres.Tune because resourceFieldRef would hand over 100 % of limits.memory with no headroom:

yaml
# Go service with CPU and memory limits, the cgroup values passed to the Go
# runtime through the downward API, and an optional sandboxed runtime.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
spec:
  replicas: 3
  selector:
    matchLabels: { app: orders-api }
  template:
    metadata:
      labels: { app: orders-api }
    spec:
      # runtimeClassName: gvisor     # run this pod under runsc (see runtimeclass.yaml)
      hostUsers: false               # user namespace: UID 0 in the pod is not UID 0 on the node
      terminationGracePeriodSeconds: 30
      containers:
        - name: app
          image: ghcr.io/acme/orders-api@sha256:<digest>
          resources:
            requests: { cpu: "500m", memory: "256Mi" }   # scheduling + cpu.weight
            limits:   { cpu: "2",    memory: "512Mi" }   # cpu.max "200000 100000", memory.max
          env:
            # No GOMEMLIMIT here: the downward API would pass 100% of limits.memory
            # (zero headroom). The app calls cgroupres.Tune(10) at start-up, which
            # sets ~90% of memory.max; an explicit env value would override that.
            # Go 1.25+ modules derive GOMAXPROCS from cpu.max; older go.mod lines do not.
            - name: GOMAXPROCS
              valueFrom:
                resourceFieldRef: { resource: limits.cpu, divisor: "1" }
          securityContext:
            runAsNonRoot: true
            runAsUser: 65532
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: { drop: ["ALL"] }
            seccompProfile: { type: RuntimeDefault }

The Go angle ​

  • Version gate. Container-aware GOMAXPROCS arrived in Go 1.25 and follows the go line of the main module, not the toolchain: a 1.27 toolchain building a go 1.24 module keeps the old default. Either raise the go line, set //go:debug containermaxprocs=1, set GOMAXPROCS, or call a package like this one. runtime.SetDefaultGOMAXPROCS (Go 1.25) re-enables the default after an explicit override.
  • Requests are ignored. The runtime "does not consider the 'CPU requests' option". A pod with requests.cpu: 1 and no limit still gets GOMAXPROCS = node CPUs; the Go blog names "a small container receiving 2 CPUs running on a 128 core machine" as the worst case and suggests an explicit limit or GOMAXPROCS.
  • Rounding. Go rounds a 2.5-CPU limit up to 3 (and anything below 2 up to 2) so the full quota is usable; automaxprocs floors to 2 with a minimum of 1. Either is defensible; the important part is not 64.
  • GOMEMLIMIT is soft. It makes the GC work harder as the heap approaches the limit; it does not cap memory outside the runtime (cgo, mmap'd files, the binary). Keep 5-10 % headroom below memory.max, and pair it with a sane GOGC (a very low limit with a large live heap leads to GC thrashing rather than an OOM).
  • cgroup v1 and v2. v2 uses cpu.max/memory.max; v1 uses cpu.cfs_quota_us/cpu.cfs_period_us and memory.limit_in_bytes, where "unlimited" is a huge number rather than max. Parents count: a limit on the pod slice applies even if the container scope says max.
  • Signals. As PID 1 the Go binary receives SIGTERM only because signal.NotifyContext/signal.Notify installs a handler (see OS Processes, Signals & Graceful Shutdown); without one the kernel's init protection drops it.
  • Goroutines are not threads. GOMAXPROCS caps threads running Go code, not goroutines; blocking syscalls get extra threads that do not count against it, and those still consume CPU quota. The scheduler itself is covered in Goroutines & Channels.

Laravel ​

Before ​

A pool file copied from a VM with 8 GB of RAM, now running in a container with limits.memory: 512Mi:

ini
; www.conf copied from the old VM (8 GB RAM) into a container with limits.memory: 512Mi
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
; 50 workers x ~45 MiB = ~2.2 GiB possible inside a 512 MiB cgroup -> OOMKilled at peak

After ​

A pool sized for the cgroup: static, children computed from memory, recycling and status endpoints:

ini
; /usr/local/etc/php-fpm.d/www.conf (excerpt) for a php-fpm container with a
; 512 MiB memory limit and a 1-CPU limit. Workers are processes: each one
; costs its own resident memory, all charged to the container's cgroup.
[www]
listen = 9000

; static: a fixed pool, no spawning under load, memory use is predictable.
; dynamic: between min/max spare servers; ondemand: spawn on request, idle
; workers exit after pm.process_idle_timeout.
pm = static

; max_children * peak RSS per worker must fit under memory.max with headroom
; for the master, OPcache shared memory and the page cache.
; (512 MiB - 96 MiB reserve) / 48 MiB per worker = 8
pm.max_children = 8

; Recycle a worker after N requests to cap slow leaks (0 = never).
pm.max_requests = 500

; Used only with pm = dynamic / ondemand:
;pm.start_servers = 2
;pm.min_spare_servers = 1
;pm.max_spare_servers = 3
;pm.process_idle_timeout = 10s

; Expose the pool's live counters to the Nginx sidecar / probes.
pm.status_path = /fpm-status
ping.path = /fpm-ping

; A request that runs past the stop grace period is killed anyway: keep it shorter.
request_terminate_timeout = 25s

An entrypoint helper that recomputes pm.max_children from memory.max at start-up (so one image fits several limits) and execs php-fpm so it stays PID 1:

bash
#!/bin/sh
# Entrypoint helper: size the php-fpm pool from the cgroup memory limit, then
# exec php-fpm as PID 1. Writes a pool override that loads after www.conf.
#   CGROUP_ROOT    cgroup v2 directory of this container (default /sys/fs/cgroup)
#   FPM_CONF_DIR   php-fpm pool directory (default /usr/local/etc/php-fpm.d)
#   FPM_CHILD_MB   measured peak RSS of one worker in MiB (default 48)
#   FPM_RESERVE_MB memory kept for the master, OPcache and page cache (default 96)
set -eu
root=${CGROUP_ROOT:-/sys/fs/cgroup}
conf=${FPM_CONF_DIR:-/usr/local/etc/php-fpm.d}
child=${FPM_CHILD_MB:-48}
reserve=${FPM_RESERVE_MB:-96}

limit=$(cat "$root/memory.max" 2>/dev/null || echo max)
if [ "$limit" = max ]; then
  echo "fpm-tune: no memory limit, keeping pm.max_children from www.conf" >&2
else
  mb=$((limit / 1024 / 1024))
  children=$(((mb - reserve) / child))
  [ "$children" -lt 1 ] && children=1
  printf '[www]\npm = static\npm.max_children = %s\n' "$children" > "$conf/zz-pm.conf"
  echo "fpm-tune: memory.max=${mb}MiB reserve=${reserve}MiB child=${child}MiB -> pm.max_children=$children" >&2
fi
exec "$@"

An Artisan command that shows the cgroup limits next to PHP's settings (useful in CI smoke tests and kubectl exec); php -l clean; Artisan::command closure commands live in routes/console.php per the Laravel 13 Artisan docs:

php
<?php
// routes/console.php (excerpt): print what the container allows next to what
// PHP and FPM are configured to use, so a pool that cannot fit is caught in CI.
use Illuminate\Support\Facades\Artisan;

Artisan::command('container:limits {--child-mb=48} {--reserve-mb=96}', function () {
    $read = fn (string $f): ?string => is_readable($f) ? trim((string) file_get_contents($f)) : null;

    $memMax = $read('/sys/fs/cgroup/memory.max');        // bytes or "max" (cgroup v2)
    $cpuMax = $read('/sys/fs/cgroup/cpu.max');           // "200000 100000" or "max 100000"

    $limitMb = ($memMax !== null && $memMax !== 'max') ? intdiv((int) $memMax, 1024 * 1024) : null;
    [$quota, $period] = $cpuMax !== null ? explode(' ', $cpuMax) + [1 => '100000'] : ['max', '100000'];
    $cpus = $quota === 'max' ? null : round((int) $quota / (int) $period, 2);

    $this->table(['setting', 'value'], [
        ['cgroup memory.max (MiB)', $limitMb ?? 'no limit'],
        ['cgroup CPUs (cpu.max)', $cpus ?? 'no limit'],
        ['php memory_limit', ini_get('memory_limit')],
        ['suggested pm.max_children', $limitMb === null ? 'n/a'
            : max(1, intdiv($limitMb - (int) $this->option('reserve-mb'), (int) $this->option('child-mb')))],
        ['suggested Octane --workers', $cpus === null ? 'n/a' : (string) max(1, (int) ceil($cpus))],
    ]);
})->purpose('Show cgroup limits and the php-fpm / Octane sizes that fit them');

The Laravel angle ​

  • The process manager vs cgroup limits. php-fpm is a master plus N worker processes; the cgroup charges all of them (and OPcache's shared memory, and page cache) against one memory.max. Measure a worker's peak RSS under real traffic (ps -o rss on the workers, or memory.peak on a test pod with one worker), then pm.max_children = (memory.max - reserve) / peak RSS. Too many children turns a traffic spike into an OOM kill; too few turns it into queued requests, which is the failure you want.
  • static vs dynamic vs ondemand in containers. The orchestrator scales by adding pods, so a fixed pool per pod (static) is the predictable choice; dynamic saves memory only when the node can use it for something else; ondemand adds start-up latency per worker and suits rarely used admin pools.
  • CPU. php-fpm workers are single-threaded; with limits.cpu: 1, eight busy workers share one CPU of quota. That is fine for I/O-bound Laravel requests; CPU-heavy endpoints need more CPU or fewer workers per pod.
  • Octane keeps the app in memory and starts "an application request worker for each CPU core provided by your machine" by default: inside a container that is the node's cores, so pass --workers matching the CPU limit and --max-requests to recycle.
  • Queue workers run one PHP process each: php artisan queue:work --memory=128 --max-jobs=1000 --max-time=3600 exits a worker before it grows past its share ("The --memory option specifies the memory limit in megabytes at which the worker should exit"), and the container restart policy or Supervisor starts a fresh one. Size the worker container's limit to memory x workers plus headroom.
  • PID 1 and stop signals. The official php-fpm image uses STOPSIGNAL SIGQUIT for a graceful FPM stop; keep exec "$@" in entrypoints so php-fpm (not sh) is PID 1 and receives it. request_terminate_timeout should be shorter than the grace period.
  • Logs and state go to stderr and Redis/the database, never the container layer (copy-up and loss on removal, see OverlayFS).

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
p99 spikes, nr_throttled growsMatch runtime parallelism to cpu.maxGOMAXPROCS (go.mod 1.25+, env, package), Octane --workersSmooth CPU use within quotaSpiky workloads lose short bursts
Random OOMKilled under loadSize from memory, set soft limitsGOMEMLIMIT ~90 %, static FPM pool from memory.maxBack-pressure instead of killsNeeds measured RSS
docker stop takes 10 s, work lostPID 1 that handles signalsExec form, exec "$@", signal handler, --init/tiniGraceful drainsMust also bound drain time
Zombies, fork failsReaping init--init, tini, shareProcessNamespaceStable PID countOne more binary/flag
Distroless container, no tools to debugHost tools in its namespacesnsenter --target <pid> --net ..., kubectl debugNo image changesNeeds node access or debug permissions
Root in container = root on hostUser namespacesRootless Podman/Docker, hostUsers: falseBreakout lands unprivilegedPort < 1024, bind-mount ownership, kernel support
Untrusted code on shared nodesSandbox runtimeRuntimeClass gVisor or KataSecond isolation boundarySyscall overhead or per-pod VM cost
Library misreads limits on v2v2-aware readerUpgrade (Go 1.25+ for CPU), or read cpu.max/memory.max yourselfCorrect sizingMust test both layouts
kubelet and runtime disagree on cgroupsOne drivercgroupDriver: systemd + SystemdCgroup = trueCorrect accounting, no fights with systemdNode reconfiguration
Database in container layer is slow and lostVolumesBind/volume mounts bypass overlay copy-upNative filesystem speed, persistenceVolume lifecycle to manage

Throttling that looks like slowness ​

Read cpu.stat in the container's cgroup twice, a minute apart: if nr_throttled / nr_periods is more than a few percent, the service is hitting cpu.max. Before raising the limit, set GOMAXPROCS (or worker counts) to the limit; then decide between a higher limit, no limit with a request (better utilisation, less predictable), or more replicas.

OOM kills that the app never logs ​

The kernel kills with SIGKILL, so the app cannot log. Evidence lives outside: memory.events (oom_kill), dmesg (the kernel log names the killed process), Kubernetes lastState.terminated.reason: OOMKilled. Fix in order: measure (memory.peak), make the runtime aware (GOMEMLIMIT, FPM pool size, Octane --max-requests), then set the limit to measured peak plus headroom.

Graceful stop that actually drains ​

Make the app PID 1 (exec form, exec "$@"), install a SIGTERM handler, finish in-flight work within the grace period (Docker 10 s, Kubernetes 30 s by default), and add tini or --init if the app spawns children. Verify with docker stop timing: a correct container stops in well under the timeout.

Debugging a container that has nothing inside ​

Find the host PID (docker inspect, crictl inspect), then nsenter --target <pid> --net for network tools, cat /proc/<pid>/status for capabilities and seccomp, cat /proc/<pid>/cgroup plus the cgroup files for limits; or kubectl debug -it <pod> --image=busybox --target=<container> to share its PID namespace without node access.

Running untrusted workloads ​

Install a sandbox runtime on a dedicated node pool (gVisor or Kata), register it in containerd and as a RuntimeClass, and select it per pod. Keep the default seccomp profile and dropped capabilities as well: the sandbox is an additional layer, not a replacement.

Choosing ​

Which isolation ​

WorkloadChooseWhy
Your own services, trusted imagesrunc or crun containersNative speed, full compatibility
Untrusted or customer code on shared nodesgVisor (runsc)Syscalls served in user space; small overhead for CPU-bound code
Multi-tenant with strong isolation, full kernel ABIKata Containers (QEMU, Cloud Hypervisor or Firecracker)Hardware virtualisation per pod
Functions / per-request sandboxes at high densityFirecracker microVMs"< 125 ms" boot, "< 5 MiB" VMM overhead
Different OS or kernel, legacy appliancesFull VM (or KubeVirt)Own kernel, any OS
"A machine" with systemd, SSH, several daemonsLXD / Incus system containerVM-like management, container density
Plugin or edge code with tiny footprintWasm via a containerd shimMillisecond start, capability-based sandbox

Which engine and runtime ​

ContextEngine / high-level runtimeOCI runtimeNotes
Developer laptop (macOS/Windows)Docker Desktop or Podman machinerunc / crun inside the VMLinux VM is part of the product
Linux developer boxDocker Engine or rootless Podmanrunc / crunRootless where possible
CI runners (GitHub Actions, GitLab)Docker on hosted runners; rootless Podman/BuildKit on self-hostedrunc / crunAvoid --privileged Docker-in-Docker
Kubernetes nodescontainerd 2.x (or CRI-O)runc default, crun/youki optional, runsc/kata via RuntimeClassSystemd cgroup driver
Single-host productionDocker Engine with live-restore, or Podman + Quadletrunc / crunsystemd supervises Podman containers

Which cgroup setup ​

QuestionAnswer
v1 or v2?v2 everywhere; Kubernetes deprecates v1 (v1.35) and runc recommends kernel 5.2+
cgroupfs or systemd driver?systemd on systemd hosts, same driver in kubelet and runtime
CPU limit or only a request?Limit + matching GOMAXPROCS/workers for predictable latency; request only for best utilisation of idle CPU
memory.max only or also memory.high?memory.max always; memory.high (Kubernetes MemoryQoS) to get throttling before OOM
pids.max?Always set (Docker --pids-limit, kubelet PodPidsLimit)

Which php-fpm pool mode ​

ModeUse in containers whenSize by
staticDefault for web pods; scaling is by replicas(memory.max - reserve) / worker peak RSS
dynamicPods share nodes with bursty neighbours and memory matters at idlepm.max_children as above; spare servers small
ondemandRarely used admin/back-office poolspm.max_children as above, pm.process_idle_timeout
Octane (FrankenPHP/Swoole/RoadRunner)High-throughput APIs--workers = CPU limit, --max-requests

In architecture: from a single process to a distributed system ​

Every layer above the kernel can be swapped (Docker for Podman, containerd for CRI-O, runc for crun or gVisor), but the kernel contract (namespaces, cgroups, OverlayFS, capabilities, seccomp) is the same everywhere. Architecture decisions are therefore about where limits are set, who owns the runtime layer, and how much isolation each tenant needs.

Monolith: one host, a few containers ​

A Laravel monolith on one VM: Nginx and php-fpm containers plus a queue worker, run by Docker Compose (or Podman with Quadlet units). What this chapter adds to that setup: memory and CPU limits per service in the Compose file (deploy.resources.limits), a php-fpm pool sized from that limit (static, max_children from memory.max), queue workers with --memory/--max-jobs, pids limits so a runaway exec cannot starve the box, --init for anything that spawns children, and live-restore so a Docker upgrade does not restart production. Debugging happens with host tools against container namespaces, because the containers carry no tools.

Modular monolith: one codebase, several container roles ​

The same image runs as web, worker, scheduler and a Go sidecar (PDF rendering, image processing). Each role gets its own cgroup budget: the web role is latency-sensitive (CPU limit with matching worker count), the worker role is throughput-oriented (no CPU limit, a request, memory per job), the Go sidecar sets GOMAXPROCS and GOMEMLIMIT from its own limits. Sharing a network namespace (Kubernetes pod, Compose network_mode: service:web) lets the sidecar listen on localhost without exposing a port.

Microservices: many images, many teams, one runtime layer ​

Twenty services on Kubernetes. The platform team owns the node image and runtime: containerd 2.x with the systemd cgroup driver, runc as default, gVisor or Kata registered as RuntimeClass handlers on a sandboxed node pool, cgroup v2 everywhere. Node pools and their runtime configuration are provisioned with Terraform (for example a dedicated node pool whose nodes have gVisor or Kata installed). Service teams own their limits and the runtime tuning that matches them, encoded once in the golden-path Helm chart:

text
1  Helm chart values: resources.limits.cpu / memory per service, runtimeClassName optional
2  chart template injects GOMAXPROCS via resourceFieldRef; the app sets GOMEMLIMIT from memory.max
3  Argo CD syncs the chart; kubelet -> CRI -> containerd creates cgroups under kubepods.slice
4  CI (GitHub Actions or GitLab CI) runs a smoke test: `container:limits` / `tune` inside the image
5  alerts on container_cpu_cfs_throttled_periods_total and OOMKilled restarts per service

Builds run on CI runners; on self-hosted GitHub Actions or GitLab runners that build images, rootless BuildKit or Podman avoids giving every pipeline root on a shared host. The Nginx ingress controller and other node-level DaemonSets get explicit limits too, because they share nodes with everything else. Architecture-level reasoning (why containers and orchestration at all, service mesh placement) is in Containers & Kubernetes.

Distributed data: stateful containers and noisy neighbours ​

Databases, caches and brokers in containers meet the kernel layer hardest. memory.max counts page cache, so a PostgreSQL or Kafka container whose working set lives in page cache can be reclaimed aggressively or OOM-killed at a limit that looks generous; size the limit for shared buffers plus the cache you want, use memory.high/memory.min where the platform exposes them, and keep data on volumes, never in the overlay upper layer (copy-up of large files, loss on removal). I/O isolation (io.max, io.weight) and PSI (io.pressure) protect a database's latency from batch neighbours. Replicas of one database belong on different nodes (anti-affinity), because containers on one node share one kernel, one page cache and one disk queue. For untrusted multi-tenant data processing, per-tenant microVMs (Firecracker, Kata) give each tenant its own kernel and page cache.

Scaling path: 1x, 10x, 100x ​

ScaleRuntime layerLimits and tuningIsolation and operations
1x (one host)Docker Engine or Podman, runc/crun, cgroup v2Limits per Compose service, static FPM pool, GOMAXPROCS/GOMEMLIMIT set--init, live-restore, host tools via nsenter
10x (one cluster)containerd 2.x, systemd driver, node images built centrallyLimits in the Helm golden path, throttling and OOM alerts, kubelet PodPidsLimithostUsers: false where supported, RuntimeClass for risky workloads
100x (many clusters, tenants)Several runtime handlers per node pool (runc, gVisor, Kata/Firecracker), Wasm shims for edgeAutomated right-sizing (VPA recommendations), PSI-based alertsSandboxed pools for untrusted code, per-tenant microVMs, kernel patch cadence as a platform SLO

Lab ​

Label: this build environment is macOS with no Linux VM and no Docker (AUTHORING cost rule), so every unshare, nsenter, mount, cgroup, ip, runc, ctr, crictl and docker command below is expected, not run. Their expected output is either quoted from the man page or spec that documents it (named at each step) or written as <placeholders>, never invented numbers. Steps marked ran on the host were executed on macOS (Go 1.27.4, darwin/arm64) and show real output.

1. Test the cgroup reader (ran on the host) ​

bash
cd docs/snippets/platform/containers-under-the-hood/go
gofmt -l . && go vet ./... && GOOS=linux go vet ./... && go test -race -count=1 ./...
# ok  	academy/containers-under-the-hood/cgroupres	1.399s
# ?   	academy/containers-under-the-hood/cmd/tune	[no test files]

2. Plan GOMAXPROCS and GOMEMLIMIT from real and fixture cgroups (ran on the host) ​

bash
go run ./cmd/tune                      # macOS: no /proc/self/cgroup
# before: GOMAXPROCS=12 NumCPU=12 GOMEMLIMIT=9223372036854775807
# no cgroup found (not Linux?): leaving the runtime defaults alone

go run ./cmd/tune -root cgroupres/testdata/v2-pod -apply
# before: GOMAXPROCS=12 NumCPU=12 GOMEMLIMIT=9223372036854775807
# cgroup v2 path=/ cpu=2.50 memory.max=536870912
# plan: cpu limit 2.50 CPUs -> GOMAXPROCS=3
# plan: memory.max 536870912 -> GOMEMLIMIT=483183810 (10% headroom)
# after: GOMAXPROCS=3 GOMEMLIMIT=483183810

go run ./cmd/tune -root cgroupres/testdata/v2-host-view   # limit only on the pod's parent slice
# before: GOMAXPROCS=12 NumCPU=12 GOMEMLIMIT=9223372036854775807
# cgroup v2 path=/kubepods.slice/pod-a.slice/cri-abc.scope cpu=0.50 memory.max=1073741824
# plan: cpu limit 0.50 CPUs -> GOMAXPROCS=2
# plan: memory.max 1073741824 -> GOMEMLIMIT=966367620 (10% headroom)

GOMAXPROCS=8 go run ./cmd/tune -root cgroupres/testdata/v1-docker -apply
# before: GOMAXPROCS=8 NumCPU=12 GOMEMLIMIT=9223372036854775807
# cgroup v1 path=/docker/abc cpu=1.50 memory.max=268435456
# plan: GOMAXPROCS set in the environment: keep it
# plan: memory.max 268435456 -> GOMEMLIMIT=241591860 (10% headroom)
# after: GOMAXPROCS=8 GOMEMLIMIT=241591860

GOMEMLIMIT=9223372036854775807 is math.MaxInt64, the documented "off" value; the 2.5-CPU fixture rounds up to 3 and the 0.5-CPU one to the minimum of 2, as the Go 1.25 runtime does.

3. Size the php-fpm pool from a cgroup file (ran on the host, fake cgroup directory) ​

bash
cd ..                                   # back to the snippet root
d=$(mktemp -d); mkdir -p $d/cg $d/conf
echo 536870912 > $d/cg/memory.max
CGROUP_ROOT=$d/cg FPM_CONF_DIR=$d/conf php/fpm-tune.sh cat $d/conf/zz-pm.conf
# fpm-tune: memory.max=512MiB reserve=96MiB child=48MiB -> pm.max_children=8
# [www]
# pm = static
# pm.max_children = 8
echo 1073741824 > $d/cg/memory.max
FPM_CHILD_MB=64 CGROUP_ROOT=$d/cg FPM_CONF_DIR=$d/conf php/fpm-tune.sh cat $d/conf/zz-pm.conf
# fpm-tune: memory.max=1024MiB reserve=96MiB child=64MiB -> pm.max_children=14
# [www]
# pm = static
# pm.max_children = 14
echo max > $d/cg/memory.max; rm $d/conf/zz-pm.conf
CGROUP_ROOT=$d/cg FPM_CONF_DIR=$d/conf php/fpm-tune.sh true; echo exit=$?
# fpm-tune: no memory limit, keeping pm.max_children from www.conf
# exit=0

4. Namespaces with unshare and nsenter (expected, not run; outputs from unshare(1)) ​

bash
#!/usr/bin/env bash
# Namespaces by hand with util-linux. Linux only; run as root unless noted.
# Expected output is quoted from unshare(1) and namespaces(7); not run here.
set -euo pipefail

# 1. Every process already lives in one namespace of each type.
ls -l /proc/$$/ns            # cgroup ipc mnt net pid pid_for_children time ... user uts
lsns --task $$               # same list, with the namespace inode numbers

# 2. New PID + mount namespace; --fork makes the command PID 1 there,
#    --mount-proc remounts /proc so ps/readlink see the new PID numbers.
unshare --fork --pid --mount-proc readlink /proc/self      # prints: 1

# 3. New UTS namespace: the hostname change is invisible to the host.
unshare --uts sh -c 'hostname demo-box; hostname'          # demo-box
hostname                                                   # unchanged

# 4. Unprivileged user namespace (no root needed): uid 1000 becomes root inside.
unshare --user --map-root-user sh -c 'whoami; cat /proc/self/uid_map'
#   root
#            0       1000          1

# 5. A namespace outlives its processes if a bind mount keeps it open.
touch /root/uts-ns
unshare --uts=/root/uts-ns hostname FOO
nsenter --uts=/root/uts-ns hostname                        # FOO
umount /root/uts-ns

# 6. A "container" from parts: new pid, mount, uts, ipc, net, cgroup namespaces.
unshare --fork --pid --mount-proc --uts --ipc --net --cgroup \
  sh -c 'hostname box; ip link; ps -ef; cat /proc/self/cgroup'
#   only "lo" (DOWN) in ip link, ps shows sh as PID 1, cgroup reads "0::/"

The man page's own outputs: unshare --fork --pid --mount-proc readlink /proc/self prints 1; unshare --user --map-root-user sh -c 'whoami; cat /proc/self/uid_map /proc/self/gid_map' prints root and 0 1000 1 twice; with /etc/subuid = 1000:100000:65536 and --map-auto, a file chowned to 1:1 inside shows as 100000 100000 outside.

5. A cgroup v2 limit, throttling and an OOM kill (expected, not run) ​

bash
#!/usr/bin/env bash
# cgroup v2 by hand: create a group, limit it, load it, read the accounting, clean up.
# Linux with the unified hierarchy at /sys/fs/cgroup; root. Expected, not run here.
set -euo pipefail
cg=/sys/fs/cgroup/demo

test -f /sys/fs/cgroup/cgroup.controllers && echo "cgroup v2"   # v1 has no such file
cat /sys/fs/cgroup/cgroup.controllers        # cpuset cpu io memory hugetlb pids rdma misc

# Controllers must be enabled in the PARENT's subtree_control to appear in children.
echo "+cpu +memory +pids +io" > /sys/fs/cgroup/cgroup.subtree_control
mkdir -p "$cg"

echo "50000 100000" > "$cg/cpu.max"          # 50 ms per 100 ms period = 0.5 CPU
echo 200            > "$cg/cpu.weight"       # 2x the default 100 under contention
echo 256M           > "$cg/memory.max"       # hard limit: reclaim, then OOM kill
echo 224M           > "$cg/memory.high"      # throttle and reclaim before the hard limit
echo 0              > "$cg/memory.swap.max"  # no swap for this group
echo 64             > "$cg/pids.max"         # fork bombs stop at 64 tasks
echo "8:0 wbps=10485760" > "$cg/io.max"      # 10 MiB/s writes to device 8:0

# Load 1, CPU: a busy loop started inside the group (the child writes its own PID
# into cgroup.procs, then execs). This shell stays outside, so it survives.
sh -c "echo \$\$ > $cg/cgroup.procs; exec yes > /dev/null" &
cpu_pid=$!
sleep 10
cat "$cg/cpu.stat"        # usage_usec ... nr_periods nr_throttled throttled_usec
cat /proc/$cpu_pid/cgroup # 0::/demo
kill "$cpu_pid"

# Load 2, memory: tail buffers /dev/zero (no newline ever) and grows until memory.max.
sh -c "echo \$\$ > $cg/cgroup.procs; exec tail /dev/zero" || true   # killed by the OOM killer
cat "$cg/memory.events"   # low high max oom oom_kill oom_group_kill ...
cat "$cg/memory.peak"     # close to 256M
cat "$cg/pids.current"    # 0 again
cat "$cg/memory.pressure" # PSI: some avg10=... full avg10=...

# Cleanup: a cgroup can be removed only when it has no processes.
rmdir "$cg"
bash
# Expected shape of the reads inside the script (taken before the final rmdir):
# cpu.stat after 10 s of `yes` at 0.5 CPU
# usage_usec <about 5000000>
# user_usec <n>
# system_usec <n>
# nr_periods <about 100>
# nr_throttled <about nr_periods: the loop exhausts every period>
# throttled_usec <n>
# memory.events after `tail /dev/zero` hit memory.max
# low 0
# high <n>          (memory.high = 224M was crossed first: throttling, no kill)
# max <n>
# oom 1
# oom_kill 1
# oom_group_kill 0  (memory.oom.group left at 0)

The key names are the ones cgroup-v2.rst defines for cpu.stat and memory.events; the values depend on the host.

6. OverlayFS copy-up and whiteouts (expected, not run) ​

bash
#!/usr/bin/env bash
# OverlayFS by hand: two read-only layers, one writable layer, one merged view.
# Linux, root. Expected, not run here.
set -euo pipefail
cd "$(mktemp -d)"
mkdir -p lower1 lower2 upper work merged
echo "from base"  > lower2/base.txt
echo "v1"         > lower2/config.yml
echo "from app"   > lower1/app.txt

# lowerdir is a colon list, top first: lower1 is stacked above lower2.
mount -t overlay overlay \
  -o lowerdir=lower1:lower2,upperdir=upper,workdir=work merged
ls merged                    # app.txt base.txt config.yml

echo "v2" > merged/config.yml   # copy_up: the whole file is copied into upper, then written
cat lower2/config.yml           # v1   (lower layers never change)
ls upper                        # config.yml

rm merged/base.txt              # whiteout: a 0/0 character device in upper
ls -l upper/base.txt            # c--------- 1 root root 0, 0 ... upper/base.txt
ls merged                       # app.txt config.yml

mkdir merged/newdir && touch merged/newdir/x
getfattr -d -m trusted upper/newdir 2>/dev/null || true   # opaque dirs carry trusted.overlay.opaque

umount merged
# What Docker/containerd do for a container: lowerdir = image layers (one
# directory per layer), upperdir = the container layer, merged = its rootfs.
mount | grep overlay | head -n1   # classic overlay2 store: overlay on /var/lib/docker/overlay2/<id>/merged

Expected: after the write, upper/config.yml exists and lower2/config.yml still says v1 (lower layers are never modified); after rm, upper/base.txt is a character device with device number 0/0, which overlayfs.rst defines as a whiteout.

7. A container from scratch, then the same with runc (expected, not run) ​

bash
#!/usr/bin/env bash
# A container from scratch: namespaces + pivot_root + /proc, no runtime.
# Linux, root, ROOTFS = an unpacked image (e.g. docker export busybox | tar -x).
# Expected, not run here.
set -euo pipefail
ROOTFS=${ROOTFS:-/tmp/busybox-rootfs}

if [ "${1:-}" != inner ]; then
  # New mount, PID, UTS, IPC, network and cgroup namespaces; re-exec this script inside.
  exec unshare --mount --pid --fork --uts --ipc --net --cgroup "$0" inner
fi

hostname mini
mount --make-rprivate /                   # stop mount events leaking to the host
mount --bind "$ROOTFS" "$ROOTFS"          # pivot_root needs new_root to be a mount point
cd "$ROOTFS"
mkdir -p .oldroot
pivot_root . .oldroot                     # new root mount; old root parked under .oldroot
umount -l /.oldroot && rmdir /.oldroot    # detach the host filesystem entirely
mount -t proc proc /proc                  # a /proc that matches the new PID namespace
mount -t tmpfs tmpfs /tmp
exec /bin/sh                              # PID 1 of the namespace (no init: no reaping!)

# chroot "$ROOTFS" /bin/sh would only change pathname resolution for one process:
# same mount table, same PID/network view, and root can climb out with chroot+cd ..
bash
#!/usr/bin/env bash
# Run an OCI bundle with runc directly, then walk the OCI lifecycle by hand.
# Linux, root, runc installed; docker only to export a rootfs. Expected, not run here.
set -euo pipefail
mkdir -p /mycontainer/rootfs && cd /mycontainer
docker export "$(docker create busybox)" | tar -C rootfs -xf -
runc spec                                  # writes a template config.json (terminal: true, sh)

# Option 1: create + start + delete in one go (interactive sh)
runc run demo1

# Option 2: the lifecycle operations of the OCI runtime spec
# PID 1 must install a SIGTERM handler, or the kernel drops SIGTERM sent from the
# host (pid_namespaces(7)); a bare "sleep 300" would ignore "runc kill ... TERM".
jq '.process.terminal=false | .process.args=["sh","-c","trap \"exit 0\" TERM; while :; do sleep 1; done"]' \
  config.json > c && mv c config.json
runc create demo2        # namespaces, cgroup, mounts set up; user program NOT started
runc state demo2         # "status": "created", "pid": <pid of runc init>
runc start demo2         # exec the user program
runc state demo2         # "status": "running"
runc ps demo2
runc kill demo2 TERM     # PID 1 has a TERM trap: exits within ~1 s (the current sleep 1 finishes first)
sleep 2
runc state demo2         # "status": "stopped"
# Without a handler: runc kill demo2 KILL (SIGKILL is always delivered from outside)
runc delete demo2        # remove what create made (cgroup, state dir)

# Rootless variant: a config with user namespace mappings, state kept in a user dir.
runc spec --rootless && runc --root /tmp/runc run demo3

Expected runc state output has the OCI state fields ociVersion, id, status (created, then running, then stopped), pid, bundle; the runc README says the unmodified runc spec template "should give you a sh session inside the container".

8. Network namespace with a veth pair and a bridge (expected, not run) ​

bash
#!/usr/bin/env bash
# What a bridge-mode container network is: netns + veth pair + bridge + NAT.
# Linux, root, iproute2 + iptables. Expected, not run here.
set -euo pipefail

ip netns add box                                  # empty netns: only lo, DOWN
ip link add br0 type bridge && ip addr add 10.10.0.1/24 dev br0 && ip link set br0 up
ip link add veth-host type veth peer name veth-box # a veth pair: packets in one end leave the other
ip link set veth-host master br0 up
ip link set veth-box netns box                    # move one end into the namespace
ip -n box addr add 10.10.0.2/24 dev veth-box
ip -n box link set veth-box name eth0             # what the container calls eth0
ip -n box link set eth0 up && ip -n box link set lo up
ip -n box route add default via 10.10.0.1

sysctl -w net.ipv4.ip_forward=1
iptables -t nat -A POSTROUTING -s 10.10.0.0/24 ! -o br0 -j MASQUERADE   # egress NAT
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to 10.10.0.2:8080  # "-p 8080:8080"

ip netns exec box ping -c1 10.10.0.1              # bridge gateway reachable
ip netns exec box ping -c1 1.1.1.1                # internet via MASQUERADE
# Docker's default bridge is the same idea: docker0 = 172.17.0.1/16, one vethXXXX per container.

9. Look at a real runtime stack and enter a container (expected, not run) ​

bash
#!/usr/bin/env bash
# Look at the runtime stack on a Linux host or Kubernetes node. Expected, not run here.
set -euo pipefail

# Docker Engine: dockerd -> containerd -> containerd-shim-runc-v2 -> container PID 1.
ps -e -o pid,ppid,cmd --forest | grep -E 'dockerd|containerd|shim|sleep' | grep -v grep
docker run -d --name s1 busybox sleep 3600
ctr --namespace moby containers list        # Docker's containers, seen by containerd
ctr --namespace moby tasks list             # TASK = container id, PID, STATUS RUNNING

# Kubernetes node: kubelet -> CRI gRPC -> containerd (namespace k8s.io) -> shim -> runc.
crictl info | grep -A2 -E '"(runc|runsc|kata)"'   # configured runtime handlers
crictl pods && crictl ps
ctr --namespace k8s.io containers list | head
systemd-cgls --no-pager /kubepods.slice | head -n 20   # pod cgroups under the systemd driver

# Which runtime engine is used and which cgroup version?
runc --version; crun --version 2>/dev/null || true
stat -fc %T /sys/fs/cgroup                  # cgroup2fs (v2) or tmpfs (v1/hybrid)
docker info --format '{{.CgroupVersion}} {{.CgroupDriver}} {{.DefaultRuntime}}'
bash
#!/usr/bin/env bash
# Enter a running container's namespaces from the host, with host tools.
# Linux host with Docker or containerd; run as root. Expected, not run here.
set -euo pipefail
name=${1:-orders-api}

# Docker: the container's init process as seen from the host PID namespace.
pid=$(docker inspect --format '{{.State.Pid}}' "$name")
# containerd/Kubernetes node instead:  crictl inspect --output go-template \
#   --template '{{.info.pid}}' <container-id>

ls -l /proc/"$pid"/ns                       # compare inode numbers with /proc/self/ns
nsenter --target "$pid" --net ss -ltnp      # listening sockets inside the container's netns
nsenter --target "$pid" --net ip addr       # eth0@ifN: the container end of a veth pair
nsenter --target "$pid" --mount --pid ps -ef   # needs ps inside the image's filesystem
nsenter --target "$pid" --mount cat /proc/1/status | grep -E 'CapEff|NoNewPrivs|Seccomp'
cat /proc/"$pid"/cgroup                     # 0::/system.slice/docker-<id>.scope
# The distroless way: keep host binaries, join only the network namespace.
nsenter --target "$pid" --net tcpdump -ni eth0 port 8080

Expected: the process forest shows containerd-shim-runc-v2 as the parent of the container's PID 1 and no runc process; docker info prints 2 systemd runc on a current cgroup v2 host with the systemd driver; stat -fc %T /sys/fs/cgroup prints cgroup2fs (Kubernetes docs).

Common misconceptions ​

BeliefReality
A container is a lightweight VMA process with namespaces, a cgroup and a reduced privilege set on the shared host kernel; no guest kernel
Containers are a security sandboxgVisor's README: "Containers are not a sandbox"; one kernel bug can break all of them; add gVisor/Kata for untrusted code
docker stop always stops the app gracefullySIGTERM to PID 1 is dropped unless PID 1 has a handler; SIGKILL follows after the timeout
PID 1 reaps zombies automaticallyOnly if it calls wait(); apps rarely do; use tini/--init
A CPU limit of 2 = 2 dedicated cores200 ms of CPU time per 100 ms period on any cores; bursts get throttled
Go 1.25+ is always container-awareOnly with go 1.25+ in go.mod; and only for CPU, never GOMEMLIMIT
CPU requests limit a containerRequests set cpu.weight and scheduling; only limits set cpu.max (Go ignores requests too)
The OOM killer runs only when the host is out of memorymemory.max triggers it inside the cgroup even on an idle host
memory.high kills like memory.maxIt throttles and reclaims; "Going over the high limit never invokes the OOM killer"
Root in a container is harmlessWithout a user namespace it is UID 0 on the host, limited only by capabilities and seccomp
chroot isolates a processchroot(2): "not intended to be used for any kind of security purpose"; containers use pivot_root in a mount namespace
Writing to a file in the container edits the imageCopy-up to the upper layer; the image layers never change
Kubernetes needs DockerThe kubelet speaks CRI; dockershim was removed in v1.24; containerd or CRI-O run the same OCI images
runc runs as long as the containerrunc exits after start; the shim (or conmon) is the parent
php-fpm adapts its worker count to the containerIt uses the pool file; size pm.max_children from memory.max yourself

Cheat sheet ​

TopicRemember
DefinitionContainer = process + namespaces (see) + cgroup (use) + rootfs via pivot_root (files) + caps/seccomp (ask)
Namespacesmnt, uts, ipc, pid, net, user, cgroup, time; compare /proc/<pid>/ns/* inodes
PID 1Signals only if handled (SIGKILL/SIGSTOP from outside always); adopts orphans; its death kills the namespace
Toolsunshare --fork --pid --mount-proc, nsenter --target <pid> --net, lsns, ip netns
User namespacesRoot inside, unprivileged outside; /etc/subuid; rootless Docker/Podman; hostUsers: false
cgroup v2One tree; cgroup.controllers present; leaves only; subtree_control enables controllers
CPUcpu.max = quota period (throttle), cpu.weight (share); watch nr_throttled
Memory, pids, iomemory.max (OOM in group), memory.high (throttle), memory.events oom_kill, PSI; pids.max; io.max (rbps wbps riops wiops)
OverlayFSlowerdir=top:...:bottom, upperdir + workdir on one fs; whole-file copy-up; 0/0 whiteout; opaque dirs
OCIRuntime spec: bundle = rootfs + config.json; states created/running/stopped; image + distribution specs for the rest
Stackdocker -> dockerd -> containerd -> shim -> runc; kubelet -> CRI -> containerd/CRI-O; podman -> conmon -> crun
Runtimesrunc (Go), crun (C, faster), youki (Rust), runsc (gVisor), kata (VM)
Isolation choiceTrusted: runc; untrusted: gVisor/Kata via RuntimeClass; functions: Firecracker; other OS: VM
Gogo 1.25+ in go.mod for automatic GOMAXPROCS (ceil, min 2); always set GOMEMLIMIT ~90 % of memory.max
PHP-FPMpm = static, pm.max_children = (memory.max - reserve) / worker RSS, pm.max_requests; Octane --workers = CPU limit

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is a container, in terms of kernel features, and why is it not a VM? Must-know ​

Answer

Answer: It is an ordinary process tree that the kernel shows a private view of the system through namespaces (PID, network, mount, UTS, IPC, user, cgroup, time), whose consumption a cgroup meters and caps, whose root filesystem is an OverlayFS mount entered with pivot_root, and whose privileges are cut by capabilities, seccomp and no_new_privs. There is no guest kernel and no emulated hardware: all containers on a host make system calls to the same kernel, which is why they start in milliseconds and why a kernel bug can cross container boundaries. See Container definition.

2 — Your app runs as PID 1 and docker stop always takes 10 seconds. Explain the kernel rule and two fixes. Must-know ​

Answer

Answer: The kernel delivers a signal from outside to a PID namespace's init only if init has installed a handler for it (SIGKILL and SIGSTOP excepted). An app (or /bin/sh from a shell-form CMD) without a SIGTERM handler ignores it, so Docker sends SIGKILL after its 10-second timeout. Fix by handling SIGTERM in the app and using exec form / exec "$@" so the app really is PID 1, or by running a minimal init (docker run --init, tini) that has handlers and forwards the signal to the app. See PID 1.

3 — What is the difference between cgroups v1 and v2, and how do you tell which one a host uses? Must-know ​

Answer

Answer: v1 mounts one hierarchy per controller (cpu,cpuacct, memory, pids ...) with inconsistent rules; v2 has a single unified hierarchy, processes only in leaf cgroups, controllers enabled through cgroup.subtree_control, new interfaces such as memory.high, cpu.max and PSI, and safe delegation. A host is on v2 if /sys/fs/cgroup/cgroup.controllers exists, or if stat -fc %T /sys/fs/cgroup/ prints cgroup2fs. Kubernetes deprecated v1 in v1.35. See cgroups v1 vs v2.

4 — A Go service with limits.cpu: 2 on 64-core nodes has p99 spikes of ~100 ms. What is happening and how do you fix it? Must-know ​

Answer

Answer: cpu.max allows 200 ms of CPU time per 100 ms period. If GOMAXPROCS is 64 (the module's go.mod is below 1.25, or GOMAXPROCS is set to the node size), dozens of threads exhaust the quota early in each period and the whole cgroup is throttled until the next one; cpu.stat shows nr_throttled growing. Make GOMAXPROCS match the limit: raise the go.mod go line to 1.25+ (the runtime then derives it, rounding up with a minimum of 2), set GOMAXPROCS from the downward API, or read cpu.max at start-up as in the Go package. See Cgroup-aware runtimes.

5 — What happens, step by step, when a container's memory reaches memory.max? Must-know ​

Answer

Answer: The kernel first tries to reclaim memory charged to the cgroup (page cache, then anonymous memory to swap if memory.swap.max allows). If usage cannot be reduced, memory.events counts max and then oom, and the OOM killer is invoked inside the cgroup, killing a process there (or the whole group with memory.oom.group = 1) and counting oom_kill. If PID 1 is killed the container exits with 137 (128 + SIGKILL); Kubernetes reports OOMKilled. memory.high, by contrast, only throttles and reclaims. See Controllers, limits and OOM.

6 — Explain lowerdir, upperdir, workdir, copy-up and whiteouts in OverlayFS. Important ​

Answer

Answer: lowerdir is a colon-separated list of read-only layers, the leftmost on top; upperdir is the writable layer that receives every change; workdir is an empty directory on the same filesystem as upperdir used to prepare copy-ups and whiteouts atomically; the merged mount is what the process sees. Writing to a lower file first copies the whole file (metadata, data, xattrs) up into upperdir; deleting a lower file creates a whiteout (a 0/0 character device, or .wh.<name> in OCI layer tarballs) that hides it, and a recreated directory becomes opaque. Lower layers never change. See OverlayFS.

7 — Who does what in docker run: dockerd, containerd, the shim and runc? Must-know ​

Answer

Answer: dockerd serves the Docker API and owns networks, volumes and log drivers; containerd owns images (content store, snapshotters) and container metadata and starts a shim per container; the shim (containerd-shim-runc-v2) calls runc and then stays as the container's parent, holding stdio and reporting the exit status over ttRPC; runc reads the bundle's config.json, creates namespaces, cgroup and mounts, execs the process and exits. Because the shim is the parent, containerd and dockerd can restart without killing containers. See Docker Engine and Podman and containerd, shim and CRI.

8 — Why did Kubernetes remove dockershim, and what runs containers on a node now? Important ​

Answer

Answer: The kubelet talks to runtimes only through the CRI, a gRPC API; Docker Engine never implemented CRI, so Kubernetes carried an adapter (dockershim) and removed it in v1.24. Nodes run containerd (with its built-in CRI plugin) or CRI-O, which execute the same OCI images Docker builds through an OCI runtime such as runc or crun. Since v1.26 the kubelet requires the v1 CRI API. See containerd, shim and CRI.

9 — How do user namespaces make rootless containers possible, and what are their typical limitations? Important ​

Answer

Answer: A user namespace maps IDs: the process is UID 0 with a full capability set inside the namespace, but those capabilities apply only to resources owned by that namespace, and outside it is an unprivileged UID (often from a subordinate range in /etc/subuid via newuidmap). Rootless Docker and Podman run the engine and containers that way. Limitations: no binding of ports below 1024 by default, user-space networking (pasta, slirp4netns) is slower, bind-mounted host files show unmapped owners, and some storage or device features need kernel support. See User namespaces and rootless.

10 — Why does chroot not isolate a process, and what do runtimes use instead? Important ​

Answer

Answer: chroot only changes where pathname resolution starts for one process; the mount table, PID and network views stay shared, and the man page shows how root escapes with mkdir foo; chroot foo; cd ... Runtimes create a mount namespace, make mounts private, mount the image as a new root, call pivot_root to make it the root mount, and detach the old root so the host filesystem is no longer reachable. See Mount namespace.

11 — When would you choose gVisor, Kata Containers or Firecracker over runc? Important ​

Answer

Answer: When the code is untrusted or tenants must not share a kernel attack surface. gVisor serves syscalls in a user-space kernel written in Go (good for CPU-bound untrusted code, slower for syscall-heavy I/O); Kata runs each pod in a lightweight VM with its own guest kernel (full Linux ABI, VM overhead); Firecracker is the minimal VMM for very dense, fast-booting microVMs (AWS Lambda and Fargate). On Kubernetes each is a containerd runtime handler selected by a RuntimeClass. See Sandboxes and microVMs.

12 — How do you size pm.max_children for a php-fpm container with a 512 MiB limit? Important ​

Answer

Answer: php-fpm does not read cgroup limits, and every worker's memory counts against the same memory.max. Measure the peak RSS of one worker under realistic load (say 48 MiB), reserve memory for the master, OPcache shared memory and page cache (say 96 MiB), and set pm.max_children = (512 - 96) / 48 = 8, preferably with pm = static and pm.max_requests to recycle workers; scale with replicas, not with more children. An oversized pool turns a traffic spike into an OOM kill instead of queued requests. See Laravel.

13 — What does GOMEMLIMIT do, and why set it below memory.max? Good to know ​

Answer

Answer: It is a soft limit on memory managed by the Go runtime (heap and runtime structures, not the binary's mappings or cgo memory): as total runtime memory approaches it, the GC runs more often instead of letting the heap grow by GOGC alone. Set it to roughly 90-95 % of memory.max (the GC guide suggests 5-10 % headroom) so non-runtime memory still fits under the hard limit; no Go version sets it from the cgroup automatically. See Cgroup-aware runtimes.

14 — What is the difference between a system container (LXC/Incus) and an application container (Docker/Podman)? Good to know ​

Answer

Answer: Both use the same kernel features. A system container runs a whole distribution with its own init (systemd), services and SSH and is managed like a lightweight VM (LXD and Incus also manage real VMs); an application container runs one service from an OCI image, with the app itself as PID 1, and is built by CI and scheduled by an orchestrator. See LXC, LXD and Incus.

Glossary ​

TermMeaning
ContainerA process tree with its own namespaces, a cgroup, an overlay root filesystem and reduced privileges, sharing the host kernel
Process isolationLimiting what a process can see and use, as opposed to virtualising hardware
NamespaceKernel wrapper that gives processes their own instance of one global resource
Mount namespace (mnt)Private mount table; the first namespace (Linux 2.4.19)
UTS namespacePrivate hostname and NIS domain name
IPC namespacePrivate System V IPC objects and POSIX message queues
PID namespacePrivate PID numbering with its own PID 1
Network namespace (net, netns)Private interfaces, routes, firewall rules and ports
User namespacePrivate UID/GID mapping; root inside, unprivileged outside
Cgroup namespacePrivate view of the cgroup tree (/proc/self/cgroup shows 0::/)
Time namespacePer-namespace offsets for CLOCK_MONOTONIC and CLOCK_BOOTTIME (Linux 5.6)
clone(2) / unshare(2) / setns(2)Create a process in new namespaces / move the caller into new ones / join existing ones
unshare(1) / nsenter(1) / lsns(8)util-linux tools to create, enter and list namespaces
uid_map / gid_mapFiles that define a user namespace's ID mapping
/etc/subuid, newuidmapSubordinate ID ranges and the setuid helper that lets unprivileged users map them
RootlessEngine and containers running in a user namespace without host root (rootless Docker, Podman)
userns-remapDocker mode with user namespaces for containers but a root daemon
hostUsers: falseKubernetes pod field that runs the pod in its own user namespace (stable v1.36)
PID 1 / initFirst process of a PID namespace; adopts orphans; receives only handled signals
ZombieExited process not yet reaped with wait() by its parent
SubreaperProcess marked with PR_SET_CHILD_SUBREAPER that adopts orphaned descendants
tini / docker-initMinimal init that forwards signals and reaps zombies; docker run --init
Signal forwardingAn init passing SIGTERM and other signals on to its child
chrootChanges the root for pathname resolution only; not a security boundary
pivot_rootMakes a new mount the root mount of the mount namespace and moves the old one aside
Mount propagationWhether mounts propagate between namespaces (shared, private, slave)
veth pairTwo linked virtual Ethernet devices; one end in the container netns, one on the host
BridgeVirtual switch on the host joining veth ends (docker0, cni0)
cgroup (control group)Kernel grouping of processes for accounting and limits, exposed as a filesystem
cgroup v1 / v2One hierarchy per controller / one unified hierarchy (official in Linux 4.5)
Controllercgroup subsystem for one resource: cpu, memory, io, pids, cpuset, hugetlb ...
cgroup.subtree_controlFile in which a parent enables controllers for its children
No internal process constraintcgroup v2 rule: only leaf cgroups (and the root) hold processes
cgroup driverWho writes cgroup files: cgroupfs (runtime directly) or systemd (via D-Bus)
cpu.maxCPU bandwidth limit quota period in microseconds
cpu.weightProportional CPU share under contention (default 100)
CPU throttlingPausing a cgroup that used its quota until the next period (nr_throttled)
memory.max / memory.highHard memory limit (OOM) / throttle limit (reclaim, no OOM)
OOM killerKernel mechanism that kills a process when memory cannot be reclaimed; per cgroup with memory.max
memory.eventsCounters low, high, max, oom, oom_kill, oom_group_kill
io.maxPer-device read/write bandwidth and IOPS limits
pids.maxMaximum number of tasks in a cgroup
PSIPressure stall information: share of time tasks stalled on CPU, memory or I/O
Resource accountingThe usage counters every controller keeps (cpu.stat, memory.current, io.stat)
OverlayFSLinux union filesystem merging read-only lower dirs and one writable upper dir
lowerdir / upperdir / workdir / mergedRead-only layers / writable layer / staging dir on the upper's filesystem / combined view
Copy-up (copy_up)Copying a lower file into the upper dir on first write access
WhiteoutUpper-layer marker (0/0 char device; .wh. file in OCI layers) that hides a lower entry
Opaque directoryUpper directory marked trusted.overlay.opaque=y (.wh..wh..opq in OCI layers) hiding the lower one
Snapshottercontainerd component that turns image layers into mountable filesystems (overlayfs)
OCIOpen Container Initiative (2015): image, runtime and distribution specifications
OCI runtime specStandard for the bundle, config.json and container lifecycle
OCI image spec / distribution specStandards for image format and the registry HTTP API
BundleDirectory with config.json and a root filesystem, the input of an OCI runtime
config.jsonOCI runtime configuration: process, root, mounts, namespaces, cgroups, seccomp
Container lifecycleOCI states creating, created, running, stopped; operations create, start, kill, delete
OCI hookscreateRuntime, createContainer, startContainer, poststart, poststop (prestart deprecated)
runcReference OCI runtime in Go, from Docker's libcontainer
crunOCI runtime in C, faster start and smaller footprint
youkiOCI runtime in Rust
containerdCNCF-graduated container daemon: images, snapshots, tasks, CRI plugin
ShimPer-container process between containerd and the OCI runtime (containerd-shim-runc-v2), speaks ttRPC
ttRPCLightweight gRPC variant used between containerd and shims
CRIContainer Runtime Interface: the kubelet's gRPC API to runtimes
CRI-OKubernetes-only CRI runtime using conmon and runc/crun
dockershimFormer kubelet adapter for Docker Engine, removed in Kubernetes v1.24
dockerdDocker daemon: API, networks, volumes, delegates execution to containerd
PodmanDaemonless, Docker-compatible engine with pods and rootless by default
conmonPer-container monitor used by Podman and CRI-O
RuntimeClassKubernetes object mapping a name to a CRI runtime handler (runc, runsc, kata)
LXC / LXD / IncusSystem-container tools: the library and CLI / Canonical's manager / the community fork
System containerContainer running a full distribution with its own init
gVisor (runsc)Application kernel in Go (Sentry, Gofer) with an OCI runtime
Kata ContainersOCI runtime that runs each pod in a lightweight VM
FirecrackerKVM-based minimal VMM for microVMs (AWS Lambda, Fargate)
microVMMinimal virtual machine with a reduced device model, fast boot and small overhead
runwasicontainerd shims for WebAssembly runtimes (Wasmtime, WasmEdge)
CapabilitiesRoot privileges split into units (CAP_NET_ADMIN, CAP_SYS_ADMIN ...)
seccompKernel syscall filter; Docker's default blocks around 44 syscalls
no_new_privsProcess flag that prevents gaining privileges through setuid/file capabilities
GOMAXPROCSMax OS threads running Go code at once; container-aware by default with go.mod 1.25+
GOMEMLIMITGo runtime soft memory limit (Go 1.19+), off by default
containermaxprocs / updatemaxprocsGODEBUG settings for the Go 1.25 GOMAXPROCS behaviour
automaxprocsuber-go library that set GOMAXPROCS from the CPU quota before Go 1.25
pm (php-fpm)Process manager mode: static, dynamic, ondemand
pm.max_childrenMaximum number of php-fpm worker processes in a pool
pm.max_requestsRequests a worker serves before it is recycled

References ​

Built by Morteza Negahi