Containers and isolation: namespaces, cgroups v2, seccomp, sandboxes

What a container really is (ordinary processes on the host's kernel with private views, limits, fewer powers and a layered root), each piece built by hand and measured on a Linux 5.10 kernel, then the runtimes, sandboxes and GPU containers on top. A child page of Topic: operating-systems. Data as of October 2026. Reading: 51 min, plus 14 in closed details.

The idea

A container is not a thing the kernel knows about: it is ordinary processes on the host's one kernel, given a private view (namespaces), a budget (cgroups), fewer powers (capabilities, seccomp, LSMs) and a layered root file system (an image). Because the kernel is shared, a container keeps well-behaved jobs apart but is not a security boundary like a VM: hostile code needs another kernel in the way.

Fig. 1: one kernel, many containers, step by step

  1. One kernel, ordinary processes. Two containers on one machine, an illustrative pair: a training job (python train.py and two DataLoader workers) and a notebook. To the kernel floor below they are just processes; "container" is not a kernel object.
  2. SEE: namespaces. Each group gets a private view: its own PID numbers, mount table, network stack, hostname, IPC, user IDs, cgroup path and clocks. The sleep 60 container of section 9 was PID 1 inside and PID 68321 on the VM (sections 1 to 3).
  3. USE: a cgroup. A budget for the whole group, workers included: memory.max, cpu.max, io.max, pids.max. Usage that reaches the ceiling is pushed back: reclaim, a failed fork, an OOM kill (sections 4, 5).
  4. HAVE: an image. Read-only layers plus one writable layer, merged by overlayfs into the container's /; the image measured here, kb-os-cont:1, has six (section 3).
  5. DO: the gate. Capabilities, seccomp and LSMs check each system call before the kernel acts: Docker's default 14 capabilities, and a filter that refused perf_event_open with EPERM (sections 6 to 8).
  6. Nothing else in between. An allowed call runs the host kernel's own code, the same kernel for both containers. Everything a runtime such as Docker does is a sequence of ordinary system calls (section 0 makes them by hand, section 9 shows who makes them for real), and a kernel bug reachable through an allowed call is a way out: hostile code needs another kernel in the way (section 10).

You need: what a process, fork, exec and signals are (Processes and the system-call API) and section 8 of Topic: operating-systems, which reads these four restrictions from inside one container; its Debug lab reproduces the OOM kill, the /dev/shm limit, CPU throttling and the pids limit. This page goes one level down: how each restriction works in the kernel (Linux v5.10, the kernel these runs used), what it costs, where it bites a training or serving job, and the command that shows it.

Owned elsewhere, linked where they come up: the OOM killer and its score (Virtual memory), cpu.weight and cpu.max throttling (Scheduling and CPU time), hypervisors, the IOMMU and GPU passthrough (Virtualization and the GPU driver stack), Kubernetes as a system (Kubernetes for ML) and sandboxing agents as a security design (Agent security).

New terms (each defined again where it is taught):

namespace: a private copy of one global kernel table (PIDs, mounts, network...)
cgroup, controller: a group of processes in one tree; the code that limits one resource for it
overlayfs, copy-up, whiteout: layers merged into one tree; a file copied to the writable layer on first write; a marker that hides a deleted name
OCI image, bundle: a manifest, a config and layer archives; a root file system plus config.json
capability: one of about 40 slices of root's power
user namespace, rootless: its own user-ID numbering; root inside, an ordinary user outside
seccomp-bpf: a small program run on every system call entry
LSM: a mandatory policy checked on objects (AppArmor, SELinux, Landlock)
runtime, shim: runc and containerd; the per-container parent process
gVisor, microVM: a kernel in user space; a minimal VM with its own kernel
CDI: a file listing what giving a container a device means
QoS class: Kubernetes' Guaranteed, Burstable or BestEffort
In one screen: eight things to remember
  1. A container is processes plus restrictions. The same kernel runs it; a kernel bug reachable through an allowed system call is a way out. Code you do not trust needs a sandbox with its own kernel or a kernel in user space (section 10).
  2. Namespaces are cheap, except the network one. Creating a UTS, PID, cgroup or time namespace took 3 to 5 microseconds here; a network namespace took 2.4 ms (section 1).
  3. When PID 1 of a container dies, the kernel SIGKILLs everything else in it. A shell or --init between docker stop and Python lost the checkpoint in all three such setups here (0.24 to 0.27 s, exit 143); exec, a forwarding trap, or Python as PID 1 saved it in 1.3 to 1.9 s (section 2).
  4. memory.max kills; memory.high stalls. The same 300 MiB allocation was OOM-killed at 190 MiB under memory.max=200M, but under memory.high=200M with no swap it hung for the full 60 s without an error, and with swap it finished in 0.3 s (section 5).
  5. Kubernetes kills the whole container on an OOM. On cgroup v2 the kubelet sets memory.oom.group=1, so a DataLoader worker going over the limit takes the main process with it; under Docker's default only the worker dies (section 5).
  6. Root inside is not all of root. Docker's 14 default capabilities cannot raise priority, pin 64 MiB of memory or mount anything; Docker's default seccomp profile changed the answer for 7 of the 12 calls probed, five of which worked without it (6, 7).
  7. Some limits are per user, not per container. io_uring rings and BPF programs on Linux 5.10 are charged to the UID: two containers running as the same UID shared one 64 KiB budget, and root's was already spent (section 7).
  8. Kubernetes requests become cgroup files by formulas you can check: requests.cpu becomes cpu.weight (1 CPU gives 39 under runc 1.1, 100 under newer runc), limits.cpu becomes cpu.max, limits.memory becomes memory.max, the QoS class becomes oom_score_adj (section 12).
How this page was measured, and the OSTEP chapter map

Docker Desktop's Linux VM on an Apple M1 laptop (Linux 5.10.104-linuxkit, arm64, 5 CPUs, about 10 GB, cgroup v2 with the cgroupfs driver), Docker 20.10.17 with runc v1.1.2, October 2026, image kb-os-cont:1 (the root's lab image plus busybox, tini 0.19 and dumb-init 1.2.5). No container was privileged. Two experiments needed one extra right each, stated where used: --cap-add SYS_ADMIN to create namespaces and to remount the container's own cgroup subtree writable; --security-opt seccomp=unconfined where Docker's default filter blocks the very call being taught (pivot_root, or unshare(CLONE_NEWUSER) as a non-root user). This kernel has no pressure stall information (CONFIG_PSI is not set) and no AppArmor or SELinux, so those are taught from the kernel source and documentation and tagged not run here, as are gVisor, Firecracker, GPU containers and Kubernetes itself. Labels: measured ran here; source read from source or documentation. Scripts and raw outputs: src/exp/ and src/raw/ in the repository.

OSTEP does not have a containers chapter: containers are built from mechanisms it teaches in other places. This map says where each piece starts in the book and what this page adds.

OSTEP chapterHereWhat this page adds
4 The Abstraction: The Process, 5 Process API1, 2namespaces as per-process views; PID 1 of a namespace and its kill rule
8 Multi-level Feedback, 9 Proportional Share4, 12proportional share for groups: cpu.weight, and Kubernetes' conversion to it
13 to 23 Virtualizing memory5memory charged to a group; memory.max, memory.high, swap, group OOM
39 Files and Directories, 40 File System Implementation3mount namespaces, pivot_root, overlayfs layers, copy-up, whiteouts
53 to 57 Security (Introduction, Authentication, Access Control)6 to 8capabilities, user namespaces, seccomp-bpf, AppArmor, SELinux, Landlock
Appendix: Virtual Machines10gVisor and Firecracker: where a container ends and a VM begins (the virtualization child page owns hypervisors)

OSTEP is free at pages.cs.wisc.edu/~remzi/OSTEP. Read chapter 55 (Access Control) alongside sections 6 and 7 here.

Each call changes exactly one thing the process can see or do; changed values are highlighted, the old value struck through

The call
What the process sees now

Every value was printed by that run measured (src/raw/minictr.txt). It ran inside a Docker container started with --cap-add SYS_ADMIN --security-opt seccomp=unconfined, so that it could do what runc does on the host: create namespaces, mount, and call pivot_root (which Docker 20.10's default profile blocks). Beforehand a shell script made a busybox root file system for the overlay's lower layer and a cgroup /ctr with memory.max 64 MiB, memory.swap.max 0 and pids.max 16 (src/exp/minictr.sh).

0. A container in ten system calls

A container runtime in about 170 lines of C (src/exp/minictr.c) starts as an ordinary root process, applies one restriction per step, and after each step prints everything the process can observe: its PID, hostname, namespace numbers, how many processes and mounts it sees, its network interfaces, its cgroup and visible limits, its capabilities and seccomp state. Then it execves a busybox shell that runs a small workload. Step through it before the mechanisms: every later section explains one of these steps. The steps are numbered from 0, as the program numbers them.

  1. Start: an ordinary root process. The baseline, inside the outer Docker container: its namespaces, 22 entries in /, 23 mounts, eth0, the outer cgroup /init, and no seccomp filter (the outer container ran unconfined). It creates one System V shared memory segment, to watch at step 6.
  2. A new UTS namespace. Only the uts namespace number and the hostname change. The outer container still has its own hostname: this process now has a private copy (kernel side: unshare_nsproxy_namespaces).
  3. A new PID namespace, then fork. The child is PID 1 with parent 0 (its parent is outside the namespace): the pid becomes 1 only after the fork, because unshare sets only pid_ns_for_children (alloc_pid in fork.c). Yet it still sees 3 processes: /proc is the old namespace's until step 4 mounts a new one.
  4. Join the limited cgroup, then a cgroup namespace. /proc/self/cgroup becomes 0::/ (this cgroup looks like the root), but the visible memory.max is still the outer container's 1.5 GB: a cgroup namespace changes how paths are shown, and the mounted cgroup file system is the old view until step 4 remounts it.
  5. A mount namespace, an overlay root, pivot_root. The busybox tree is now / and the old root is unmounted: one visible process, seven root entries, eight mounts. The host's tree is gone from this mount namespace, not merely hidden. The new cgroup2 mount shows /ctr as its root: memory.max 64 MiB, pids.max 16.
  6. A network namespace. eth0 is gone; lo, tunl0 and ip6tnl0 are new devices of the new namespace (all down), two tunnel devices this kernel creates in every namespace (setup_net, about 2.4 ms, section 1). A real runtime would now add one end of a virtual Ethernet pair.
  7. An IPC namespace. The System V shared memory segment created at step 0 is no longer visible: zero segments.
  8. Drop capabilities to Docker's default 14. CapEff drops from a82425fb (Docker's 14 plus CAP_SYS_ADMIN) to a80425fb, Docker's 14: bit 21 gone. Root can still chown, but sethostname and mount now fail with EPERM.
  9. no_new_privs and a seccomp filter. Seccomp becomes 2 (filter mode) and NoNewPrivs 1. mkdir and unshare fail before reaching the kernel's code for them; getpid is unaffected (seccomp_run_filters).
  10. execve the workload. busybox sh replaces the program and keeps every restriction. The cgroup limits bite: a fork past 16 tasks fails, and a 100 MB allocation is OOM-killed inside the 64 MiB group while the shell survives. The deleted /etc/passwd becomes a whiteout in the upper layer (the workload's output and the upper layer are under the card).

1. Namespaces: a private view of one global resource

ch. 4 to 5 (the process), then beyond source namespaces(7); include/linux/nsproxy.h v5.10

The problem. Many things in Linux are global: process IDs, the mount table, network interfaces and ports, the hostname, System V shared memory, user ID numbers. Two training jobs on one machine would see each other's processes, could bind the same port and would share one /tmp. We want each to believe it is alone, without a second kernel.

How it works. 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" (namespaces(7)). In the kernel it is one pointer per kind: every task's task_struct (the processes page walks it) points to a small struct nsproxy holding one pointer per namespace kind, and code that looks up a global thing ("which network interfaces exist") follows the current task's pointer first. Two processes with different pointers see different worlds; the kernel underneath is one.

Fig. 2: the same process seen from outside and inside

  1. One pointer per kind. The process at step 0 of section 0, in front, and the outer container's processes, behind, share one nsproxy: eight pointers to the outer container's namespaces. readlink /proc/self/ns/* gives an inode number per namespace, such as net:[4026532319]; two processes with the same number share it.
  2. UTS and PID. Section 0's steps 1 and 2 swing two pointers to new namespaces: the hostname becomes trainer-0 for this process only, and the forked child is PID 1 with parent 0. Behind, nothing changed.
  3. cgroup and mount. Steps 3 and 4: the cgroup path reads 0::/; the mount table drops from 23 mounts to 8 and / from 22 entries to 7, and a fresh /proc shows one process.
  4. Network and IPC. Steps 5 and 6: eth0 is gone (only lo, tunl0, ip6tnl0), and the System V segment made at step 0 is no longer visible.
  5. Six of eight. The build never unshared the user or time namespace, so those pointers still lead to the host's: six of eight pointers now lead to new namespaces. Every number on the figure is measured (src/raw/minictr.txt), and the kernel underneath is still one.
The nsproxy fields, and the three system calls

nsproxy.h lines 31 to 41: uts_ns, ipc_ns, mnt_ns, pid_ns_for_children, net_ns, time_ns, time_ns_for_children, cgroup_ns; the user namespace lives in the task's credentials. clone(flags) starts a child in new namespaces, unshare(flags) moves the caller into new ones, setns(fd) joins an existing one through a file such as /proc/<pid>/ns/net (which is how docker exec and nsenter get in). A namespace lives while anything refers to it: a process in it, an open file descriptor of its /proc/<pid>/ns/ file, or a bind mount of that file.

The eight kinds, and what each costs to create

Kind (clone flag)What becomes privateSinceunshare() here measured
mount (CLONE_NEWNS)the mount table: what is mounted where, including / (section 3)2.4.19
UTS (CLONE_NEWUTS)hostname and NIS domain name2.6.19
IPC (CLONE_NEWIPC)System V IPC objects and POSIX message queues (not /dev/shm, which is a mount)2.6.19
PID (CLONE_NEWPID)process ID numbers; the first process is PID 1 (section 2)2.6.24
network (CLONE_NEWNET)interfaces, addresses, routes, firewall rules, ports, /proc/net2.6.29
user (CLONE_NEWUSER)user and group ID numbers and capabilities over the namespace's resources (section 6)3.8
cgroup (CLONE_NEWCGROUP)the view of the cgroup tree: your group looks like the root, 0::/4.6
time (CLONE_NEWTIME)offsets for CLOCK_MONOTONIC and CLOCK_BOOTTIME (for migrating a process between machines)5.6

"Since" is the kernel version from namespaces(7) and each kind's man page. Cost: a fresh child calls unshare(flag) once, timed around the call, 200 children per kind, median (p90) in microseconds; unshare(0) took (src/exp/ns_cost.c).

What it costs here
The UTS, PID, cgroup, time and user namespaces cost under 10 microseconds each: a small structure and a pointer swap. The mount namespace copies the caller's whole mount table (23 mounts here) and costs about 19 microseconds; the IPC namespace about 43, because it mounts a private instance of the POSIX message-queue file system (ipc/namespace.c line 58). The network namespace costs about 2.4 ms, roughly 500 times more: setup_net runs every registered per-network initialiser in turn (net_namespace.c line 341), creating a loopback device, routing tables, firewall state and per-namespace sysctls (and, on this kernel, the two tunnel devices tunl0 and ip6tnl0 of step 5). As whole commands: /bin/true took ms, unshare with five namespaces ms, and with the network namespace as well ms; docker run --rm of the same image took s (median of 5). The kernel's part of starting a container is about 1% of docker run; the rest is the daemon, containerd, the shim, runc, and setting up the image's mount and the network (section 9).
When it bites in ML
  • Multi-node training and the network namespace. A container's own network namespace reaches the outside through a virtual Ethernet pair and NAT. NCCL and RDMA jobs usually run with the host's network namespace (docker run --network host, Kubernetes hostNetwork: true) or with the RDMA device passed in, so collectives use the real interfaces.
  • DataLoader workers and /dev/shm. Workers pass batches through shared memory files in /dev/shm, which Docker mounts as a private 64 MiB tmpfs in each container (the mount namespace, not the IPC one). Too small, and workers die with "No space left on device" or a bus error (the root's Debug lab case "DataLoader workers run out of /dev/shm"). Fix: --shm-size 8g, or --ipc host, which also shares System V shared memory with the host.
  • Debugging a running job from outside. nsenter -t <pid> -n ss -tnp runs the host's ss inside the job's network namespace without a shell in the image.

Check it: lsns (every namespace and its first process), readlink /proc/<pid>/ns/*, nsenter -t <pid> -m -u -n -p, unshare --fork --pid --mount-proc bash (a shell that sees only itself), ip netns (named network namespaces, bind mounts in /run/netns).

A process calls unshare(CLONE_NEWPID) and then getpid(). What does it get?

Every namespace costs microseconds except the network one, which costs milliseconds

Who receives SIGTERM, who dies, and in what order


Times, exit codes, checkpoint files and the job's log lines are measured (src/raw/stop_matrix.txt); the step-by-step order in between is the kernel and tini source cited in each caption.

2. PID namespaces and PID 1: the stop that loses a checkpoint

ch. 5 Interlude: Process API source pid_namespaces(7); kernel/pid_namespace.c, kernel/exit.c, kernel/signal.c v5.10

The problem. Inside a container the first process must look like the init of a whole machine: PID 1, the ancestor of everything. Kubernetes and Docker stop a container by signalling exactly that process. Which process is PID 1, and what it does with the signal, decides whether your training job writes its last checkpoint.

How it works. PID namespaces nest: a process has one PID in its own namespace and another in each ancestor namespace (the sleep 60 container of section 9 was PID 1 inside and PID 68321 on the VM). The first process created in a new PID namespace gets PID 1 and becomes the namespace's init: orphans in the namespace are re-parented to it (the processes page covers reaping and zombies in section 5). Two kernel rules make it special:

  1. It ignores signals it has no handler for. The namespace's init is marked SIGNAL_UNKILLABLE, and sig_task_ignored drops a signal whose action is the default (signal.c lines 89 to 91, v5.10). SIGTERM with no handler does nothing to PID 1. SIGKILL from an ancestor namespace (the container runtime) still works.
  2. When it dies, everything else dies. "If the 'init' process of a PID namespace terminates, the kernel terminates all of the processes in the namespace via a SIGKILL signal" (pid_namespaces(7)). In the source: when init exits, find_child_reaper finds no other reaper and calls zap_pid_ns_processes (exit.c line 527), which walks every PID in the namespace and sends SIGKILL (pid_namespace.c lines 172 to 211). No handler runs; no checkpoint is written.

Rule 1 is why people add an init (docker run --init starts tini as PID 1, which forwards signals and reaps zombies). Rule 2 is the trap in that fix, which the processes page measured first: tini forwards SIGTERM to its one child; when that child is a shell running Python, the shell dies at once, tini exits, and the kernel kills Python. Below, seven ways to start the same job, each stopped with docker stop -t 10 three seconds after start. The job is a stand-in for the root's training loop: on SIGTERM it writes a checkpoint that takes about 1 s (src/exp/stopjob.py), and logs every event with a time stamp.

Seven launch styles, one docker stop: the checkpoint survives only when the process holding PID 1 outlives the job. Pick a style on the card; its steps:

    Started asdocker stop to exitExit codeCheckpoint
    Why the process-group variants (tini -g, dumb-init) fail too

    tini with TINI_KILL_PROCESS_GROUP=1 (the -g flag) and dumb-init (which signals the whole process group by default) send SIGTERM to the shell and to Python (tini.c line 526, dumb-init.c line 66). It does not help: the shell still dies at once, the init still exits with it, and the namespace's SIGKILL follows within milliseconds. Python's handler is a Python function that runs between bytecodes, after the C-level signal handler has set a flag; the job's log has no "SIGTERM received" line in either run, so the SIGKILL arrived before that function ran. What saves the checkpoint is that the process holding PID 1 outlives the job.

    The fix
    • Let Python be the process the signal reaches: exec python train.py at the end of any launcher script (the shell is replaced, keeping the PID), or the exec form CMD ["python", "train.py"] in a Dockerfile (the shell form CMD python train.py runs /bin/sh -c as PID 1).
    • If a shell must stay, make it forward and wait: python train.py & pid=$!; trap 'kill -TERM $pid' TERM; wait $pid; wait $pid (the second wait because the first returns as soon as the trap runs).
    • Install a SIGTERM handler in the job (the root's training job does); then even as PID 1 the signal is delivered.
    • With several processes per container (torchrun and its workers), let torchrun be the process that receives SIGTERM: it forwards it to the workers (Distributed Training covers elastic launch).
    When it bites in ML
    Preemptible and spot capacity, Kubernetes evictions and Slurm time limits all stop jobs this way: SIGTERM to PID 1, a grace period (Kubernetes' terminationGracePeriodSeconds, default 30 s), then SIGKILL (the processes page section 10 has the Kubernetes and Slurm sequences). In Kubernetes, shareProcessNamespace: true makes the pod's pause container PID 1 of a shared namespace (Kubernetes docs): your process is then not PID 1, so rule 1 no longer protects or hurts it, and the pause container reaps zombies.
    A Dockerfile ends with CMD python train.py (no brackets), and the script has a SIGTERM handler that checkpoints. What happens on docker stop?

    3. Mount namespaces, images and overlayfs: what files it has

    ch. 39 to 40 (files, file system implementation) source mount_namespaces(7), pivot_root(2), overlayfs docs, OCI image spec

    The problem. A training image brings its own Python, PyTorch and CUDA runtime, which must not clash with the host's or another job's. Copying a whole 2 GB file tree for every container would be slow and waste disk; ten containers of one image should share one copy.

    The mount namespace and the new root

    A new mount namespace starts as a copy of the caller's mount table; after that, mounts on either side are private (once the runtime marks its copy private, step 4 of section 0). Then the process gets a new / with pivot_root(new_root, put_old), which swaps the root mount of the whole mount namespace and moves the old one under put_old, which the runtime then unmounts: the host's tree is no longer in the namespace at all. chroot would only change where path lookups start, with the old root still mounted and reachable.

    Mount propagation, chroot against pivot_root, and why the container never calls pivot_root itself

    A new mount namespace starts as a copy of the caller's mount table; after that, mounts and unmounts on either side are private, unless mount propagation says otherwise. Each mount is shared (events propagate both ways within its peer group), slave (receives, does not send) or private. systemd makes / shared on most hosts, so a runtime first marks its copy private, recursively, or its mounts would appear on the host: that is the first mount call at step 4 of section 0 (mount(NULL, "/", NULL, MS_REC|MS_PRIVATE, NULL)).

    Then the process needs a different /. chroot(dir) only changes where path lookups start for this process; the old root is still mounted and reachable, and a process with CAP_SYS_CHROOT can break out ("This call does not change the current working directory", and it "is not intended to be used for any kind of security purpose", chroot(2)). pivot_root(new_root, put_old) instead swaps the root mount of the whole mount namespace and moves the old one under put_old, which the runtime then unmounts, so the host's tree is no longer in the namespace at all. runc uses pivot_root unless told not to (--no-pivot, for a root on a ramdisk, which cannot be pivoted; it then uses a move-mount plus chroot). Docker 20.10's default seccomp profile does not list pivot_root at all (measured: the hand-built container needed seccomp=unconfined for it): runc calls it before it installs the container's filter, and the container itself never needs to.

    overlayfs: layers, copy-up and whiteouts

    The new root is an overlay mount: several read-only lower directories (the image layers), one writable upper directory (this container's changes) and a workdir for atomic operations, merged into one tree. A lookup returns the topmost layer's version of a name. Writing to a file that exists only in a lower layer triggers a copy-up: overlayfs copies the whole file into the upper layer first (ovl_copy_up_data, fs/overlayfs/copy_up.c line 132), then lets the write proceed. Deleting a lower-layer file creates a whiteout in the upper layer, a character device with device number 0/0 that hides the name. An overlay cannot use another overlay as its upper layer (the first attempt of this page's experiment failed with EINVAL until the layers moved to a tmpfs).

    Fig. 3 steps over one real image, kb-os-cont:1 (three of its six layers drawn)

    1. Layers, and a merged view. Two read-only image layers (Debian base, 139 MB; the venv with PyTorch, 853 MB), an empty writable upper layer for this container, and the merged tree the container sees as /. Each name in the merged view comes from the topmost layer that has it: libtorch_cpu.so from the venv layer, /etc/motd from the base.
    2. First write: copy-up. A one-byte write to libtorch_cpu.so (264 MB, in an image layer) makes overlayfs copy the whole file into the upper layer before the write goes ahead: measured ms. The merged view now shows the upper copy.
    3. Second write. The file is already in the upper layer, so the write goes to that private copy: ms.
    4. Delete: a whiteout. rm /etc/motd cannot change a lower layer, so overlayfs writes a whiteout (a character device 0, 0) with the same name in the upper layer, and the merged view hides the name. docker diff shows D /etc/motd.
    5. Create: straight to the upper layer. A new file, /work/new.txt, goes directly to the upper layer with no copy ( ms) and vanishes with the container. docker diff shows A /work/new.txt. Times are measured in a Docker container on this VM (src/raw/image.txt); the whiteout's mode is from the hand-built container of section 0.
    What it costs here measured
    The first one-byte write to PyTorch's libtorch_cpu.so (264 MB, in an image layer) took ms: the whole file was copied into the container's upper layer. The second took ms. Creating a new file costs nothing extra: it goes straight to the upper layer.
    The raw outputs: the upper layer of the hand-built container, and the copy-up timing
    Inside the hand-built container measured
    $ echo hi > /etc/motd; rm /etc/passwd
    $ ls /etc
    motd
    The upper layer, seen from outside

    Columns: mode, size (or device major, minor), file. c--------- 0, 0 ./etc/passwd is the whiteout; ./etc was copied up as a directory so it could hold the two entries.

    Images: what docker pull downloads

    An OCI image is a manifest (a JSON list of content hashes), a config (environment, entry point, the ordered list of layer hashes) and the layers, each a tar archive of the files one build step added, changed or deleted (deletions stored as whiteout files). Identical layers are stored and downloaded once and shared by every image that uses them. Each RUN, COPY or ADD line of a Dockerfile makes a layer; ENV and WORKDIR only change the config (the 0B rows below).

    The real image: docker history and docker diff
    
    

    The image has 6 layers; the root mount had 7 lower directories because Docker adds one small "init" layer per container holding /etc/hosts, /etc/resolv.conf and /etc/hostname. docker diff reads the upper layer: A added, C changed, D deleted (the whiteout).

    When it bites in ML
    • Checkpoints and datasets written inside the container land in the upper layer on the node's disk: they vanish with the container, count against the node's ephemeral storage (Kubernetes evicts pods that exceed ephemeral-storage limits), and a later edit of a big file copies it up whole. Write them to a volume (a bind mount or a persistent volume is not part of the overlay); the storage page covers making them durable.
    • Model weights baked into an image make every node pull them before the job starts, and a change to one byte rebuilds and re-uploads the whole layer. Keep weights in object storage or a volume and the image for code and libraries; put the layers that change most (your code) last in the Dockerfile so the big ones (CUDA, PyTorch) stay cached.
    • pip install at container start writes thousands of files to the upper layer on every start. Bake dependencies into the image instead.

    Check it: findmnt -T / or grep ' / ' /proc/self/mountinfo (the overlay and its layers), docker history <image>, docker diff <container>, docker inspect -f '{{json .GraphDriver.Data}}' (the layer directories on the host), df -h / inside (the node's disk).

    A container appends one line to a 2 GB log file that came with the image. How much new disk does that use, and when?

    4. cgroups v2: the tree, delegation, PIDs, I/O and freezing

    ch. 9 Proportional Share, applied to groups source cgroup v2 (kernel docs); kernel/cgroup/cgroup.c, kernel/cgroup/pids.c v5.10

    The problem. Namespaces hide things but limit nothing: a process in its own namespaces can still use every CPU, all memory and the whole disk bandwidth. We need to group processes, including the ones they will fork later, and give each group a budget, with accounting we can read.

    How it works. A control group (cgroup) is a directory in one tree mounted at /sys/fs/cgroup (cgroup v2, the "unified hierarchy"; v1 had one tree per controller and is legacy). Every process is in exactly one cgroup, listed in its cgroup.procs file; children of a fork start in the parent's cgroup, so a whole job stays together. Controllers (cpu, memory, io, pids, cpuset, hugetlb, rdma here) each add interface files to the directories where they are enabled, such as memory.max or pids.max. A controller is available in a cgroup's children only if it is listed in that cgroup's cgroup.subtree_control. Limits are hierarchical: nothing below can escape a limit set above.

    Two rules shape every container runtime:

    • No internal processes. A cgroup (other than the root) that has processes cannot enable domain controllers for children; otherwise the parent's own processes would compete with its children for the same budget. In the source, cgroup_vet_subtree_control_enable returns -EBUSY when the cgroup has tasks (cgroup.c lines 3203 to 3208). So processes live in leaves, and a manager first moves itself into a leaf.
    • Delegation. "A cgroup can be delegated in two ways": by giving a less privileged user write access to the directory and its cgroup.procs, cgroup.threads and cgroup.subtree_control files, or, with the nsdelegate mount option, automatically to a cgroup namespace. "Once delegated, the user can build sub-hierarchy under the directory ... and further distribute the resources it received from the parent" (cgroup v2 docs, "Delegation"). systemd does the first for a unit with Delegate=yes; rootless Podman and Kubernetes nodes running as systemd services rely on it.

    Fig. 4: a cgroup tree, and limits pushing back

    1. One tree. Inside a container with its own cgroup namespace, /sys/fs/cgroup is the container's own cgroup, shown as the root. It holds the container's 4 processes; cgroup.controllers lists cpuset, cpu, io, memory, hugetlb, pids and rdma; cgroup.subtree_control is empty. (--cap-add SYS_ADMIN was used only to remount that subtree writable; Docker mounts it read-only. measured, src/raw/cgroup.txt.)
    2. No internal processes. echo +memory > cgroup.subtree_control fails with "Device or resource busy" (EBUSY): a controller can be handed to children only once the parent holds no processes.
    3. Processes into a leaf, then delegate. The 4 processes move into a child init/; now '+memory +pids +io +cpu' is accepted and every child gets memory.*, pids.*, io.* and cpu.* files. Children of a fork start in their parent's cgroup, so a whole job stays together.
    4. pids.max pushes back on fork. A limited child: section 0's /ctr, a separate run, with pids.max 16. Starting 20 sleepers stopped at 15 tasks: the next fork failed with "can't fork: Resource temporarily unavailable" (EAGAIN) and pids.events recorded max 1.
    5. memory.max pushes back with an OOM kill. In the same group, memory.max 64 MiB with no swap: a subshell allocating 100 MB was killed (exit 137, oom_kill 1) and the shell around it survived. Section 5 compares this wall with the brake, memory.high.
    6. io.max slows the stream. Another run: reading 64 MiB with O_DIRECT took unlimited and under io.max 254:0 rbps=20000000. Nothing fails: the reads simply take longer.
    The session, as recorded
    
    

    src/raw/cgroup.txt. Note dash's built-in echo reports any write error as "I/O error"; /bin/echo shows the real one.

    Three small controllers, measured

    pidspids.max caps tasks (processes and threads) in the group; a fork over it fails with EAGAIN and pids.events counts it (pids_can_fork, pids.c line 218). With pids.max 16, starting 20 sleepers in the hand-built container failed with "can't fork: Resource temporarily unavailable" and pids.events recorded max 1.
    ioio.max caps bytes or I/Os per second per device. Reading 64 MiB with O_DIRECT: without a limit, with rbps=20000000. The key is the whole disk's major:minor (254:0), not the partition's (254:1).
    freezerWriting 1 to cgroup.freeze stops every task in the group (they show as sleeping) until 0 is written; docker pause uses it. A counting loop below stopped for the 2 s it was frozen.

    The cpu controller (cpu.weight, cpu.max, throttling) belongs to the scheduling page, which measured both knobs and the throttling that makes a step four times slower; memory is the next section.

    When it bites in ML
    • The pids limit counts threads. PyTorch, OpenMP and every DataLoader worker start threads; a Kubernetes pod PID limit or --pids-limit sized for "processes" fails at fork or thread creation (the root's Debug lab case "BlockingIOError on fork: the pids limit counts threads too").
    • io.max throttles data loading silently: the reads simply take longer, and only io.stat and the step time show it. Shared nodes use it (and io.weight) to stop one job's data pipeline from starving another's checkpoint writes.
    • Buffered writes are charged to the cgroup that dirtied the pages, so a checkpoint's writeback counts against the job's own I/O and memory limits (the storage page, section 5).

    Check it: cat /proc/<pid>/cgroup (which cgroup), systemd-cgls, systemd-cgtop, and the files themselves: cgroup.controllers, cgroup.subtree_control, pids.current, pids.events, io.stat, cgroup.events.

    A counting loop stops dead for the 2 s its cgroup is frozen, then resumes

    Iterations per 0.5 s, measured.

    One allocation, three limits

    5. Memory limits: memory.max kills, memory.high stalls

    ch. 13 to 23, applied to a group source cgroup v2: memory; mm/memcontrol.c v5.10

    The problem. A training job's memory grows: DataLoader workers copy pages on write, a prefetch queue fills, a leak creeps. On a shared node something must stop one job before it takes memory from the others. There are two ways to stop it, a wall and a brake, and they fail very differently.

    How it works. The memory controller charges each page to the cgroup of the task that first touched it: anonymous memory (heap, tensors), page cache from the files it reads and writes, and kernel memory on its behalf (socket buffers, slab). memory.current is the total. Four knobs act on it; the virtual memory page explains the OOM killer and how it picks a victim, so here we measure the knobs against each other.

    FileWhat happens at the boundary
    memory.maxthe wall: "If a cgroup's memory usage reaches this limit and can't be reduced, the OOM killer is invoked in the cgroup"
    memory.highthe brake: "the processes of the cgroup are throttled and put under heavy reclaim pressure. Going over the high limit never invokes the OOM killer and under extreme conditions the limit may be breached"
    memory.swap.maxhow much of the group may be swapped out (0: none, so anonymous memory cannot be reclaimed at all)
    memory.min, memory.lowprotection: memory below them is not reclaimed (min) or reclaimed only as a last resort (low) when others need memory

    Quotes from the kernel's cgroup v2 documentation, memory interface files.

    The brake: over memory.high the kernel reclaims, then puts the task to sleep on its way back to user space, up to 2 s each time, growing with the square of the overage; if nothing can be freed, it sleeps again on the next allocation, indefinitely.

    The brake in the kernel source

    The brake in the source: when a charge pushes a group over memory.high, the kernel reclaims, and on the way back to user space mem_cgroup_handle_over_high puts the task to sleep for a penalty that grows with the square of the overage (penalty_jiffies = max_overage * max_overage * HZ, scaled, in calculate_high_delay, memcontrol.c line 2583), capped at 2 s per return to user space (MEMCG_MAX_HIGH_DELAY_JIFFIES, line 2466). If reclaim frees enough, the task runs on; if nothing can be freed, it sleeps again on the next allocation, indefinitely.

    The same input three ways: a process allocates 300 MiB, 10 MiB at a time, touching every page (src/exp/hog.py), in a cgroup capped at 200 MiB by each knob in turn (measured, src/raw/cgroup.txt).

    One allocation, three limits: the wall kills at once, the brake without swap stalls with no error, the brake with swap finishes. Pick a limit on the card; what the run shows:

    1. Under the wall. memory.max=200M, no swap. Each 10 MiB is copied at full speed (a few milliseconds a step) and memory.current, the charge, follows the request.
    2. Up to the wall. Still full speed up to MiB; the next 10 MiB will not fit under 200 MiB.
    3. Killed. The next allocation could not be charged and nothing could be reclaimed: the cgroup's OOM killer sent SIGKILL (exit 137, oom_kill 1). Fast, loud, unambiguous.

    Who dies: memory.oom.group

    By default the OOM killer kills one process, the one with the highest score in the group. With memory.oom.group=1, "all tasks belonging to the cgroup or to its descendants ... are killed together or not at all". Measured with a long-running "main" process and a "worker" that grows past memory.max:

    memory.oom.groupworkermainmemory.events

    That difference matters because Kubernetes sets memory.oom.group=1 on every container on cgroup v2 unless the node's kubelet is configured with singleProcessOOMKill: true (kuberuntime_container_linux.go lines 314 to 319, v1.34.0; the default is false on cgroup v2, kubelet.go lines 734 to 743). Under Docker (group 0), a DataLoader worker that goes over the limit dies alone and the main process raises "DataLoader worker (pid N) is killed by signal: Killed." (the root's Debug lab case "Killed with exit code 137"). Under Kubernetes the same event kills the main process and every worker: the pod shows OOMKilled and restarts from the last checkpoint.

    Pressure stall information (PSI), the signal that would have shown the stall not run here

    PSI measures the share of wall time in which tasks were stalled waiting for memory (also CPU and I/O): some (at least one task stalled) and full (all non-idle tasks stalled at once), averaged over 10, 60 and 300 s, in /proc/pressure/memory and in each cgroup's memory.pressure (PSI docs). It is the signal that tells a stall like the "memory.high, no swap" run above from a job that is merely slow: there full would have sat near 100%. systemd-oomd kills cgroups on it (systemd-oomd). This kernel was built without it (CONFIG_PSI is not set, src/raw/env.txt), so the only trace of the stall here was the high counter in memory.events.

    When it bites in ML
    • Exit 137 and "OOMKilled" mean memory.max. Check memory.events (oom_kill) and memory.peak (Linux 5.19 and later) or your monitoring's peak; size the limit for the peak, including the page cache your data loading creates (reclaimable, but it counts until reclaimed).
    • A job that stops making progress with no error inside a cgroup with memory.high set close to its working set and no swap is throttled, not deadlocked: memory.events high keeps rising. Kubernetes' MemoryQoS feature would set memory.high for you; it is still alpha and off by default at v1.34 (kube_features.go line 1478).
    • Swap and training don't mix: a swapped-out parameter or optimizer page is a major fault on the next step. The virtual memory page measured the slowdown.

    Check it: cat memory.current memory.max memory.high memory.events memory.stat in the job's cgroup (/sys/fs/cgroup inside a container with a cgroup namespace), dmesg | grep -i "memory cgroup out of memory" on the host (not available in this VM), kubectl describe pod (Last State: OOMKilled).

    You set memory.high 10% below memory.max as an early warning, with no swap. The job's working set grows past memory.high but stays under memory.max. What happens?

    6. Capabilities and user namespaces: root, but not all of root

    ch. 55 Access Control source capabilities(7), user_namespaces(7)

    The problem. Most images run as root (user ID 0), and many programs expect to. Classic Unix has one test: UID 0 may do anything. A container's root must be able to install packages in its own file system and bind its own ports, but not load kernel modules, change the host's clock or reconfigure the host's network.

    Capabilities. Linux splits root's power into about 40 capabilities, each a bit checked by the kernel at one kind of operation: CAP_CHOWN before changing a file's owner, CAP_NET_ADMIN before reconfiguring interfaces, CAP_SYS_ADMIN (the catch-all) before mounting, and so on. Docker starts containers with 14 capabilities, CapEff 00000000a80425fb (the root page decoded them). prctl(PR_SET_NO_NEW_PRIVS) adds a one-way switch: after it, execve can never grant more privilege, not even through a setuid binary; it is what lets an unprivileged process install a seccomp filter (section 7).

    The five capability sets

    A process has several sets: permitted (what it may use), effective (what is switched on now, the set the kernel checks), inheritable and ambient (what passes across execve), and the bounding set (a ceiling no descendant can exceed). The CapEff line of /proc/<pid>/status is the effective set as a hexadecimal bit mask.

    Eight privileged operations, each needing one capability, tried in four containers (measured, src/exp/caps_ops.py):

    Port 80 worked even with no capabilities because Docker sets net.ipv4.ip_unprivileged_port_start to in each container's network namespace, so binding low ports needs no privilege there. "not allowed to raise maximum limit" is Python's message for EPERM from setrlimit.

    When it bites in ML
    • Pinned memory. pin_memory=True in a DataLoader and CUDA's cudaHostAlloc lock host pages so the GPU can copy from them by DMA (the virtual memory page). Locking is limited by RLIMIT_MEMLOCK, 64 KiB by default in these containers (src/raw/env.txt), unless the process has CAP_IPC_LOCK. Above, mlock of 64 MiB failed everywhere except with --cap-add IPC_LOCK. RDMA and GPUDirect stacks need it too: training containers usually run with --ulimit memlock=-1 or that capability.
    • Profilers and debuggers: py-spy dump, gdb -p and strace -p attach with ptrace; this page's siblings ran strace with --cap-add SYS_PTRACE. perf needs perf_event_open, which Docker's seccomp profile blocks (section 7).
    • Priorities: nice -5 for a data-feeding process failed without CAP_SYS_NICE.

    User namespaces: root inside, an ordinary user outside

    A user namespace gives a process its own numbering of user and group IDs and a full set of capabilities that apply only to resources owned by that namespace. A map in /proc/<pid>/uid_map (lines of "inside outside count") translates IDs at the boundary: files created by "root" inside are owned by the real user outside, and the host's files keep their real owners inside. Namespaces of other kinds created by a process in a user namespace are owned by it, so inside you may change the hostname of your own UTS namespace or mount a tmpfs in your own mount namespace, but not the host's. This is how rootless containers (Podman, rootless Docker, Apptainer on HPC clusters) work: a breakout lands as an ordinary user.

    The cost of user namespaces
    Every capability inside a user namespace exposes kernel code that used to be reachable only by real root (mounting some file systems, creating network devices). Canonical: "unprivileged user namespaces are now broadly used as a step in several privilege escalation exploit chains", citing Google's finding that 44% of the exploits it observed relied on them; Ubuntu 23.10 started restricting them (Ubuntu blog). Docker's default seccomp profile blocks creating them unless the container has CAP_SYS_ADMIN. Rootless gains you a lot if the container runtime has a bug; it adds kernel attack surface if the kernel has one.

    Root inside, UID 1000 outside: every capability, but only over what the namespace owns

    Static diagram of one measured session as UID 1000. Unmapped host IDs show as the overflow ID 65534 inside (user_namespaces(7)).

    The session, as recorded
    
    

    measured as UID 1000 in a container started with --user 1000:1000 --security-opt seccomp=unconfined (Docker's default profile blocks unshare(CLONE_NEWUSER) for a process without CAP_SYS_ADMIN). Inside, CapEff 000001ffffffffff is every capability, yet /etc/shadow (owned by the real root) stayed unreadable and the host's hostname unchangeable; the namespace's own new UTS and mount namespaces were fully its own. The time namespace shifted CLOCK_BOOTTIME by one day for its children only.

    7. seccomp-bpf: a filter on every system call

    beyond OSTEP source seccomp(2), kernel seccomp filter docs; kernel/seccomp.c v5.10

    The problem. Linux has about 400 system calls (Docker's default profile names 396 across its rules). A training job uses a few dozen. Every other call is kernel code an attacker can reach from inside the container; capabilities guard only some of them.

    How it works. A process installs a small program in classic BPF (a tiny register machine with loads, compares, jumps and returns; no loops) with prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) or seccomp(2). On every system call entry, before the call runs, the kernel runs the program on a struct seccomp_data: the call number, the architecture, the instruction pointer and the six argument values. The program returns an action: ALLOW, ERRNO (fail the call with a chosen error), KILL_PROCESS or KILL_THREAD, TRAP (deliver SIGSYS), LOG, TRACE, or USER_NOTIF (Linux 5.0: let a supervising process decide). Filters stack and are inherited across fork and execve; none can be removed; with several, all run and the most restrictive answer wins (seccomp_run_filters, seccomp.c lines 311 to 327). Installing one requires CAP_SYS_ADMIN or no_new_privs, so a filtered process can never execve a setuid program that would run with the filter but more privilege.

    Fig. 5: three gates on one system call, four calls measured as root in Docker's default container

    1. A call that passes. getppid() leaves the process; at entry the filter reads struct seccomp_data (call number, architecture, instruction pointer, six argument values) and allows it; it needs no capability and touches no file, so it reaches the kernel code. measured: ns per call under Docker's filter.
    2. Gate 1, the filter, at entry. perf_event_open is not in Docker 20.10's allowlist: the filter returns ERRNO and the call fails with EPERM before any kernel code for it runs.
    3. Gate 2, a capability, inside the call. nice -5 passes the filter, but the kernel's priority code asks capable(CAP_SYS_NICE), which Docker's 14 do not include: "Permission denied".
    4. Gate 3, the object. cat /etc/shadow as root of a user namespace (section 6, a run without a filter) holds every capability, but only over its own namespace: the file belongs to the real root, and the permission check on the resolved file refuses it. File permissions and LSM hooks act here, once the path has been resolved to a file.
    5. Every allowed call pays for the filter. On 5.10 the whole program runs on every call: getppid took ns with no filter and ns under Docker's; eight more trivial filters, all of which run, made it ns.
    6. What the filter cannot see. io_uring submits reads, writes and socket operations through rings of memory shared with the kernel: the filter sees one io_uring_enter, never the operations inside. Docker 25 therefore blocks io_uring_setup itself (EPERM, below).
    The filter the hand-built container installs at its step 8, all nine instructions
    /* arch first: a call number means different calls on different architectures */
    BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)),
    BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_AARCH64, 1, 0),
    BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
    BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
    BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_mkdirat, 0, 1),
    BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
    BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_unshare, 0, 1),
    BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
    BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),

    From src/exp/minictr.c. After it, mkdir and unshare failed with "Operation not permitted" and getpid worked (section 0, step 8). A filter sees argument values only: it cannot follow a pointer to read a path, because the memory could change between the check and the use. Path rules are the job of LSMs (section 8).

    Docker's default profile

    Docker's profile is an allowlist with default action ERRNO (EPERM): 340 calls allowed outright, more allowed only with a capability (mount with CAP_SYS_ADMIN) or with certain arguments (clone without namespace flags). Twelve calls probed as root with Docker's default capabilities (measured, src/exp/seccomp_probe.c; differences from "no filter" highlighted):

    The clone3 trick in Docker's profile

    One trick: clone3 passes its flags inside a structure behind a pointer, which a filter cannot read, so the profile answers it with ENOSYS ("not implemented", error 38) and glibc falls back to the old clone, whose flags are visible (default.json at v20.10.17).

    bpf and clock_settime fail even with no filter: they need capabilities the container lacks. userfaultfd is not built into this kernel. io_uring_setup failed with "Cannot allocate memory" under 20.10 for a reason that has nothing to do with seccomp: below.

    What it costs here measured
    getppid() 3,000,000 times, best of 5, nanoseconds per call (median of 3 container runs): . Docker's filter adds about ns to every system call; eight more trivial filters added ns. On 5.10 every allowed call runs the whole program; Linux 5.11 added a per-architecture bitmap of calls a filter always allows, which skips the program for them (seccomp_cache_check_allow, seccomp.c line 167, v5.11). Against the root's 316 ns read it is about a tenth: noticeable only for code that makes millions of tiny calls (the root's Debug lab case "High system time: millions of tiny reads").

    io_uring: blocked in Docker 25, and charged per user

    io_uring (the concurrency page teaches it) moves I/O submission into rings of memory shared with the kernel: one io_uring_enter call, or none with polling, submits many reads, writes, opens and socket operations, executed by the kernel. A seccomp filter sees the io_uring_enter, not the operations inside it. Docker 25.0 removed the three io_uring calls from its default profile (moby PR #46762, merged 2 November 2023), citing that "Google ChromeOS and Android have turned it off, plus all Google production servers turn it off" and that io_uring vulnerabilities have been used to break out of containers. Passing Docker 25's default.json to this 20.10 daemon reproduced it: io_uring_setup became "Operation not permitted" (table above, third column).

    The 20.10 failure is a different limit. On Linux 5.10 every ring's pages are charged against RLIMIT_MEMLOCK, but counted in user->locked_vm, a counter that belongs to the user ID, not to the process, the container or the cgroup (__io_account_mem, fs/io_uring.c lines 7863 to 7880; skipped for processes with CAP_IPC_LOCK, line 9273). Containers without a user namespace share the host's UIDs, so every container running as UID 2000 draws on one budget:

    measured src/exp/uring.sh: 1-entry rings (2 pages, 8 KiB each) created until one fails; 64 KiB allows 8. Container B, with its own namespaces and cgroup, got none while A held its rings, and 8 after A exited. Root got none even alone: other root-owned things on this VM had already used UID 0's 64 KiB.

    Why root's budget was already spent, and the kernels that fixed it

    On 5.10 BPF programs and maps are charged to the same counter (__bpf_prog_charge, kernel/bpf/syscall.c line 1631), and runc attaches a BPF program to every cgroup v2 container to enforce its device rules, so running containers alone may account for it (likely, not traced). Later kernels moved both to the memory cgroup: kernel/bpf/syscall.c no longer touches locked_vm at v5.11, and at v5.12 io_uring allocates its rings with __GFP_ACCOUNT (fs/io_uring.c line 8061, v5.12) instead of charging ring_pages to the user.

    When it bites in ML
    • Fast data readers built on io_uring fail with EPERM on Docker 25 and later and in Kubernetes runtimes with similar profiles; a library that does not fall back to ordinary reads breaks. On older kernels the same reader can fail with ENOMEM because some other container running as the same UID holds rings. Fix: a custom profile that allows io_uring, a different UID per job (or user namespaces), or --ulimit memlock high enough.
    • perf, bpftrace and some profilers need perf_event_open and bpf, blocked by default. Profile on the host, or start a debugging container with a custom profile and the needed capabilities, never --privileged on a shared node.
    • Kubernetes: securityContext.seccompProfile.type: RuntimeDefault applies the container runtime's profile; the Pod Security Standards' "restricted" level requires a profile (Pod Security Standards).

    Check it: grep Seccomp /proc/<pid>/status (0 none, 1 strict, 2 filter; Seccomp_filters counts them), docker run --security-opt seccomp=profile.json, strace -f (a blocked call shows as -1 EPERM with no other cause).

    A seccomp filter must block opening /etc/shadow but allow every other openat. Can it?

    8. Linux Security Modules: AppArmor, SELinux, Landlock not run here

    ch. 55 Access Control source LSM docs

    Capabilities and seccomp decide which kinds of operation a process may attempt. Linux Security Modules add a mandatory policy on objects: hooks throughout the kernel ask the active modules before a file is opened, a socket bound or a program executed, after the kernel has resolved the actual inode, so path tricks do not help. "Mandatory" means the file's owner cannot loosen it.

    ModulePolicy is aboutWhere you meet it
    AppArmorpaths: per-program profiles listing which files, capabilities and network access are allowedUbuntu and Debian; Docker applies its docker-default profile when AppArmor is on (Docker docs), which denies writes to most of /proc and /sys and all mounts
    SELinuxlabels: every process and file carries a type, and a policy says which types may act on whichRHEL, Fedora; containers get the container_t type and a per-container category pair so two containers cannot touch each other's files (Red Hat docs)
    Landlockunprivileged self-sandboxing: a process restricts its own file access with three system calls (Linux 5.13)sandboxes for tools and agents; Docker 25's profile allows the three landlock_* calls (the profile diff in src/inputs/)

    This VM's kernel has neither AppArmor nor SELinux (src/raw/env.txt), so the default Docker containers measured on this page had namespaces, cgroups, capabilities and seccomp, but no LSM: one layer fewer than on a typical Ubuntu or RHEL node.

    When it bites in ML
    A volume mounted from the host that the job cannot read on a RHEL node, although the Unix permissions look right, is usually SELinux labelling: mount it with the :z or :Z option so the runtime relabels it. ausearch -m avc (SELinux) or dmesg | grep apparmor on the host shows the denial.

    9. Container runtimes: who makes all those calls

    beyond OSTEP source OCI runtime spec, containerd, runc

    The problem. Sections 1 to 8 are a few hundred lines of system calls in the right order. Somebody has to pull the image, unpack the layers, write the cgroup files, create the namespaces, mount the overlay, drop the capabilities, install the filter, start the process, keep its output and report its exit code, for thousands of containers, surviving restarts of the managing daemon.

    How it works. The work is split into layers with standard interfaces between them. The OCI runtime specification defines a bundle: a root file system directory plus a config.json listing the process, its namespaces, mounts, cgroup limits, capabilities, seccomp profile and hooks. A low-level runtime (runc, written in Go; crun in C; youki in Rust) turns one bundle into one running process with exactly the system calls of section 0, then exits. A high-level runtime (containerd, CRI-O) pulls and stores images, prepares bundles, and starts one small shim process per container that becomes the container's parent, holds its standard streams, and collects its exit status, so containerd itself can restart without killing containers. Docker's daemon sits above containerd; Kubernetes' kubelet talks to containerd or CRI-O through the Container Runtime Interface (CRI).

    The real chain on this VM, from ps

    The real chain on this VM, seen from a container that shares the VM's PID namespace (--pid host, a read-only listing) while a sleep 60 container ran (measured, src/exp/runtime.sh; Docker Desktop also runs its own system services as containers under a second containerd, omitted):

    
    

    The container's process is a child of its shim, not of dockerd or containerd; runc is gone. Its PID is 68321 on the VM and 1 inside. Docker Desktop's dockerd is itself a service running under the VM's system containerd.

    When it bites in ML
    • Restarting Docker does not have to kill training: with "live-restore": true in the daemon configuration, containers keep running under their shims while dockerd restarts (Docker docs).
    • HPC clusters usually have no daemon at all: Apptainer (formerly Singularity) runs a single-file image (SIF) as the submitting user, typically sharing the host's network and PID namespaces, which suits MPI and Slurm (Apptainer docs). The GPU and InfiniBand devices are simply visible, and there is no root inside to escape from.
    • Start-up: docker run --rm took about 0.4 s here, of which the namespaces were about 4 ms (section 1). A job that starts thousands of short containers (evaluation sandboxes, RL environments) is dominated by the runtime, not the kernel.

    Who makes the calls: one long-lived daemon, one shim per container, and runc only for the moment of creation

    Static diagram. On this VM (measured) the sleep 60 container's process was PID 68321, a child of its shim, not of dockerd or containerd, and runc was gone.

    10. Sandboxes for code you do not trust not run here

    appendix Virtual Machines source gVisor security model, Firecracker design, Firecracker specification, Kata Containers

    The problem. Everything so far narrows what a container can ask of the host kernel, but the kernel answering is the host's. A container runs model-generated code, a user's notebook or an untrusted evaluation submission; one kernel bug reachable through an allowed call and the code is on the host, next to other customers' data. The fix is to put another kernel between the code and the host, and to make that kernel either smaller or isolated by hardware.

    Fig. 6: what untrusted code talks to, three designs on one host not run here

    1. Container: the host kernel answers. The code's system calls pass the gate of section 7 (about 340 allowed calls) and run the host kernel's own code. The layer an escape must break is the host kernel itself.
    2. gVisor: a kernel in user space answers. The Sentry, "an application kernel" written in Go, implements Linux's system calls itself ("Every supported call has an independent implementation in the Sentry"); the Sentry, under its own tight seccomp filter, makes only a small, enumerated set of host calls. The cost falls on code heavy in system calls and I/O.
    3. microVM: a guest kernel behind the CPU. Firecracker or Kata run a real Linux guest kernel in a minimal VM under KVM, with a device model reduced to virtio network and block, and the VMM process itself under seccomp and a jailer. Firecracker's specification: "<= 125 ms" to the guest's /sbin/init and "memory overhead <= 5 MiB" per VM.
    4. The boundary, side by side. The highlighted layer in each is what an escape must break: the shared host kernel, the Sentry, or hardware virtualization. Diagram from the gVisor and Firecracker documentation linked above.
    What the untrusted code talks toWhat protects the hostCost
    Container (runc)the host kernel, about 340 allowed callsnamespaces, cgroups, capabilities, seccomp, LSMnone measurable per call beyond seccomp (section 7)
    gVisor (runsc)the Sentry, "an application kernel" written in Go that implements Linux's system calls in user spacethe Sentry itself runs under a tight seccomp filter: "The host surface exposed to the Sentry is minimized ... explicitly enumerated and controlled"; "Every supported call has an independent implementation in the Sentry"each call is handled by the Sentry rather than the host, so the cost falls on system-call-heavy and I/O-heavy code (gVisor performance guide)
    Firecracker microVMa real Linux guest kernel in a minimal virtual machine (KVM)hardware virtualization; a device model reduced to virtio network and block devices; the Firecracker process itself under seccomp and a jailer"<= 125 ms" from start to the guest's /sbin/init; "memory overhead <= 5 MiB" per VM (Firecracker specification)
    Kata Containersa guest kernel in a lightweight VM, managed as a container through containerdhardware virtualization"The speed of containers, the security of VMs" (its tag line)

    gVisor answers "fewer, simpler host calls"; Firecracker and Kata answer "a separate kernel, enforced by the CPU". Code-execution services for language-model agents use both kinds; the agentic-harnesses topic covers the sandboxes agents use, and the virtualization child page covers hypervisors, KVM and the IOMMU.

    When it bites in ML
    • GPUs in sandboxes: a VM needs the GPU passed through (VFIO, the virtualization page); gVisor's nvproxy forwards the NVIDIA driver's ioctl calls and "supports running most CUDA applications on preselected versions of NVIDIA's open source driver" (gVisor GPU docs).
    • RL environments and evaluation harnesses that execute model output (unit-test rewards, code benchmarks) should run each episode in a sandbox of this kind, with no network unless needed, a CPU and memory cgroup limit, and a wall-clock timeout; a plain container with the default profile is not a security boundary against code written to escape it.

    11. GPU containers: the driver stays on the host not run here

    source NVIDIA Container Toolkit, CDI support, CDI specification

    The problem. The GPU's kernel driver (nvidia.ko) belongs to the host kernel, and the user-space driver library (libcuda.so) must match it exactly. The image brings the CUDA runtime and PyTorch, but must not bring its own libcuda. The container needs the device files (/dev/nvidia0, /dev/nvidiactl, /dev/nvidia-uvm), the host's matching libraries, and permission in the device cgroup to open them.

    How it works. Three pieces, all from the host, as the figure shows. The device files are bind-mounted into the container's mount namespace. The device cgroup must allow them: on cgroup v2 there is no devices.allow file; runc attaches a small BPF program to the container's cgroup that checks every device open (the same kind of program that likely used up root's locked-memory budget in section 7). The driver libraries (libcuda.so, libnvidia-ml.so, the nvidia-smi binary) are bind-mounted from the host. The NVIDIA Container Toolkit does all three. Its newer interface is the Container Device Interface (CDI), "an open specification for container runtimes that abstracts what access to a device, such as an NVIDIA GPU, means": a generated file lists, per device name such as nvidia.com/gpu=0, the device nodes, mounts, environment variables and hooks to apply (NVIDIA CDI docs).

    The device cgroup measured, and the CDI commands

    Without the BPF program's permission, a device node the container creates still cannot be opened: Virtualization and the GPU driver stack, section 9, made /dev/nvidiactl (195:255) with mknod and got EPERM on open, and with --device-cgroup-rule 'c 195:* rwm' the same open got past the cgroup and failed only with ENXIO, because no GPU driver is loaded there. CDI: nvidia-ctk cdi generate --output=/var/run/cdi/nvidia.yaml writes the file, and a CDI-aware runtime applies it on --device nvidia.com/gpu=all.

    When it bites in ML
    • "CUDA driver version is insufficient for CUDA runtime version": the image's CUDA runtime is newer than the host driver supports (the virtualization page covers driver and runtime compatibility in section 10).
    • An image that ships its own libcuda.so (copied from a build machine) shadows the host's and fails on a different driver version. Never put driver libraries in images.
    • GPU visibility is not GPU isolation: two containers given the same GPU share it by time-slicing with no memory limit between them; MIG gives hardware partitions (the virtualization page). In Kubernetes the NVIDIA device plugin advertises nvidia.com/gpu as a resource and the kubelet passes the chosen devices to the runtime.

    The image brings CUDA and PyTorch; the driver, its libraries and the device files come from the host

    Static diagram from the NVIDIA Container Toolkit and CDI documentation not run here (this VM has no GPU); the device-cgroup step was measured on the virtualization page.

    12. Kubernetes resources, mapped to cgroup files

    source Kubernetes v1.34.0: pkg/kubelet/cm/helpers_linux.go, pkg/kubelet/qos/policy.go, pkg/apis/core/v1/helper/qos/qos.go; opencontainers/cgroups v0.0.3 utils.go

    The problem. You write requests and limits in a pod spec; the kernel only understands the files of sections 4 and 5. The translation decides how much CPU a job gets under contention, when it is throttled, and which pod dies first when the node runs out of memory. Every step is a short formula in the kubelet or runc; the calculator below computes them for any pod.

    You writeThe kubelet computesThe cgroup file
    requests.cpu (milli-CPUs)cgroup v1 "shares" = milli × 1024 / 1000, at least 2, at most 262,144 (MilliCPUToShares, line 88); if only a limit is set, the request defaults to itcpu.weight, converted from shares by the OCI runtime: runc 1.1 linear, 1 + (shares - 2) × 9,999 / 262,142, so 1 CPU (1024) gives 39; the quadratic map in opencontainers/cgroups v0.0.3 and later (runc 1.3.6, 1.4.0) gives 100, the cgroup v2 default
    limits.cpuquota = milli × period / 1000 with period 100,000 us, at least 1,000 us (MilliCPUToQuota, line 61)cpu.max = "quota 100000"
    limits.memorybytesmemory.max; plus memory.oom.group=1 on cgroup v2 (section 5)
    requests.memoryused by the scheduler and for the OOM score below; memory.min only with the MemoryQoS feature gate (alpha, off)none by default
    the pod as a wholeQoS class: Guaranteed if every container has CPU and memory limits equal to its requests; BestEffort if no container sets any; Burstable otherwise (qos.go lines 157 to 174)the pod's cgroup is placed under kubepods, kubepods/burstable or kubepods/besteffort
    QoS classGuaranteed -997, BestEffort 1000, Burstable 1000 - 1000 × memory request / node memory, kept between 3 and 999 (GetContainerOOMScoreAdjust, policy.go line 45)/proc/<pid>/oom_score_adj of the container's processes (the virtual memory page explains the score)

    The weight trap, measured. This VM's Docker 20.10 uses runc v1.1.2 (src/raw/env.txt), the linear map: the scheduling page measured --cpu-shares 1024 becoming cpu.weight 39 and a CPU split matching it. A pod requesting one whole CPU therefore weighs less than a process left at the default weight 100 in a sibling cgroup. With the quadratic map, requests of 1 CPU land exactly on the default. Which one your nodes use depends on the runc (or crun) version they ship, not on Kubernetes.

    Pod to cgroup: type a pod's requests and limits, read the files the kubelet and runc write

    Leave a field empty for "not set". CPU in cores (0.5 is 500m), memory in GiB. Predict first: does removing the CPU limit from the Guaranteed training job change its cpu.weight? Then press "training job, no CPU limit".

    The weight does not change (it comes from the request); only cpu.max becomes max and the class becomes Burstable. Every formula is reproduced in src/recompute.py, which checks this calculator's JavaScript on the presets. not run here: no Kubernetes cluster was used; the formulas are read from the source files linked under the table above.

    Sources and simplifications of the calculator

    Sources (Kubernetes v1.34.0): shares and quota, helpers_linux.go lines 61 to 101; pod-level values, ResourceConfigForPod, line 124; QoS class, qos.go; OOM score, policy.go; memory.oom.group, kuberuntime_container_linux.go line 314; MemoryQoS memory.high, lines 163 to 185. Shares to weight: runc v1.1.2 utils.go line 423 (linear) and opencontainers/cgroups v0.0.3 utils.go line 425 (quadratic). Simplified: no init or sidecar containers, no pod-level resources, no hugepages, the default 100 ms CFS period, and the cgroupfs-style path names (the systemd driver writes kubepods.slice/kubepods-burstable.slice/...).

    When it bites in ML
    • CPU limits on GPU training pods throttle the data-loading and launch threads in 100 ms periods (the scheduling page measured a step four times slower). Many teams set CPU requests and no CPU limit for training, leaving the pod Burstable; Guaranteed pods with integer CPUs get exclusive cores under the kubelet's static CPU manager policy (Kubernetes docs).
    • Which pod dies when the node runs out of memory: the one with the highest oom_score_adj plus usage, so a Burstable pod with a small memory request relative to the node is first; when a container exceeds its own limit, its cgroup's OOM killer acts regardless of class.
    • os.cpu_count() still sees every CPU of the node, not the quota: size thread pools and DataLoader workers from cpu.max (the root's Debug lab case "Too many threads for the CPUs you have"). The ml-infra-and-orchestration topic covers scheduling GPUs, gang scheduling and Slurm.
    A pod has one container with requests.cpu: 4, limits.cpu: 4, requests.memory: 32Gi and no memory limit. Its QoS class?

    Depth: symptoms and rehearsal

    Symptom table: ten container failures, their cause, the check and the fix
    SymptomCauseCheckFix
    docker stop or a pod deletion loses the last checkpoint; exit 143 at oncea shell or init between the signal and Python; PID 1 died and the kernel SIGKILLed the rest (2)ps -o pid,comm inside: who is PID 1exec python, exec-form CMD, or a forwarding trap
    Stop takes exactly the grace period, then exit 137PID 1 has no SIGTERM handler and ignores it (2)grep SigCgt /proc/1/statushandle SIGTERM, or --init with Python as its direct child
    Exit 137, OOMKilled, all workers gone at oncememory.max reached; on Kubernetes memory.oom.group=1 kills the whole container (5)memory.events, kubectl describe podraise the limit to the measured peak, cut workers or prefetch
    Job stops progressing, no error, no OOMover memory.high with nothing reclaimable (5)memory.events high count rising; memory.pressure where PSI existsremove or raise memory.high
    "can't fork" or "can't start new thread" with plenty of memorypids.max counts threads (4)pids.current, pids.eventsraise the pids limit; cap OpenMP threads per worker
    Bus error or "No space left on device" in DataLoader workers64 MiB /dev/shm (1)df -h /dev/shm--shm-size or --ipc host; a memory-backed emptyDir on Kubernetes
    pin_memory, RDMA or NCCL fails to register memory64 KiB RLIMIT_MEMLOCK (6)ulimit -l--ulimit memlock=-1 or CAP_IPC_LOCK
    EPERM from perf, io_uring, unshare, mountseccomp profile or a missing capability (6, 7)grep -E 'Cap|Seccomp' /proc/self/statusadd the one capability or a custom profile; never --privileged
    io_uring ENOMEM on an older kernel with plenty of memorythe UID's locked-memory budget is shared across containers (7)same call as another UIDa UID per job, a higher memlock limit, or a kernel from 5.12 on
    First write to a big file in the image takes seconds; node disk fillsoverlayfs copy-up into the writable layer (3)docker diff, df -h /write data and checkpoints to volumes
    Interview rehearsal: six questions this page answers
    What is a container, at the kernel level?
    Not a kernel object: ordinary processes whose task_struct points at non-default namespaces (what they see), that sit in a cgroup (what they may use), with a reduced capability set, a seccomp filter and possibly an LSM profile (what they may do), and whose root is an overlay of image layers. The same kernel serves them, which is both why they start in milliseconds and why they are a weaker boundary than a VM.
    Why does a training job sometimes ignore docker stop, and sometimes die instantly without checkpointing?
    PID 1 of a PID namespace ignores signals whose action is the default, so a PID 1 without a SIGTERM handler (a shell) ignores the stop until SIGKILL. And when PID 1 exits, the kernel SIGKILLs every other process in the namespace, so an init or shell that dies on SIGTERM takes Python with it before its handler runs. Fix: the process that handles SIGTERM must be PID 1's direct target and must outlive the job's shutdown: exec, exec-form CMD, a forwarding trap.
    memory.high or memory.max for a job's limit?
    memory.max is a wall: reclaim, then OOM kill in the group. memory.high is a brake: reclaim and sleep up to 2 s per return to user space, never an OOM kill. Without swap and with anonymous memory, the brake becomes an indefinite stall that looks like a hang. Use memory.max as the limit; use memory.high only with something watching pressure (PSI) that can act.
    Why can't seccomp filter by file path, and what does?
    The filter is classic BPF over struct seccomp_data: the call number, architecture, instruction pointer and argument values. A path is behind a pointer in user memory, and reading it would race with other threads changing it. LSMs (AppArmor, SELinux, Landlock) check inside the kernel after the path is resolved to an inode.
    A pod requests 1 CPU. What cpu.weight does it get, and why might that differ between clusters?
    The kubelet converts 1000 milli-CPUs to 1024 cgroup v1 shares; the OCI runtime converts shares to a v2 weight. runc 1.1's linear map gives 39; the quadratic map in opencontainers/cgroups v0.0.3 and later (runc 1.3.6, 1.4.0) gives 100. Same pod spec, different share of a contended node, depending only on the runtime version.
    When is a container not enough isolation, and what do you use instead?
    When the code inside is hostile: one exploitable bug in any reachable kernel path gives the host. Use a sandbox that puts another kernel in the way: gVisor (a user-space kernel answering the calls, host exposed to a small enumerated set) or a microVM such as Firecracker or Kata (a guest kernel isolated by hardware virtualization), plus no network, tight cgroups and timeouts.