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
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.sleep 60 container of section 9 was PID 1 inside and PID 68321 on the VM (sections 1 to 3).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)./; the image measured here, kb-os-cont:1, has six (section 3).perf_event_open with EPERM (sections 6 to 8).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):
config.json--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).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).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).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).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 chapter | Here | What this page adds |
|---|---|---|
| 4 The Abstraction: The Process, 5 Process API | 1, 2 | namespaces as per-process views; PID 1 of a namespace and its kill rule |
| 8 Multi-level Feedback, 9 Proportional Share | 4, 12 | proportional share for groups: cpu.weight, and Kubernetes' conversion to it |
| 13 to 23 Virtualizing memory | 5 | memory charged to a group; memory.max, memory.high, swap, group OOM |
| 39 Files and Directories, 40 File System Implementation | 3 | mount namespaces, pivot_root, overlayfs layers, copy-up, whiteouts |
| 53 to 57 Security (Introduction, Authentication, Access Control) | 6 to 8 | capabilities, user namespaces, seccomp-bpf, AppArmor, SELinux, Landlock |
| Appendix: Virtual Machines | 10 | gVisor 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
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).
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.
/, 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.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./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./ 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.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.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.mkdir and unshare fail before reaching the kernel's code for them; getpid is unaffected (seccomp_run_filters).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).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
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.trainer-0 for this process only, and the forked child is PID 1 with parent 0. Behind, nothing changed.0::/; the mount table drops from 23 mounts to 8 and / from 22 entries to 7, and a fresh /proc shows one process.eth0 is gone (only lo, tunl0, ip6tnl0), and the System V segment made at step 0 is no longer visible.src/raw/minictr.txt), and the kernel underneath is still one.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.
| Kind (clone flag) | What becomes private | Since | unshare() 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 name | 2.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/net | 2.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).
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).docker run --network host, Kubernetes hostNetwork: true) or with the RDMA device passed in, so collectives use the real interfaces./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.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).
unshare(CLONE_NEWPID) and then getpid(). What does it get?unshare(CLONE_NEWPID) only sets pid_ns_for_children: the next child it forks becomes PID 1 of the new namespace. That is why the field is named "for children", and why unshare --pid needs --fork. Step 2 of section 0 shows it: the PID becomes 1 only after the fork. The time namespace works the same way.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.
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:
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.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 as | docker stop to exit | Exit code | Checkpoint |
|---|
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.
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).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).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.CMD python train.py (no brackets), and the script has a SIGTERM handler that checkpoints. What happens on docker stop?/bin/sh -c "python train.py", so the shell is PID 1: Debian's dash does not replace itself with a single command (measured: Python got PID 7, not 1). PID 1 with no SIGTERM handler ignores SIGTERM (rule 1), Python never hears about it, and after the grace period the runtime's SIGKILL kills the shell and then, by rule 2, Python: the "sh as PID 1" row above, 10.28 s and 137. Use CMD ["python", "train.py"].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.
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.
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.
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)
/. 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.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.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./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.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.$ echo hi > /etc/motd; rm /etc/passwd $ ls /etc motd
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.
docker pull downloadsAn 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).
docker history and docker diffThe 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).
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.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).
metacopy option (not enabled in this kernel's configuration), a metadata-only change such as chmod copies up only metadata; a data write always copies the whole file.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:
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.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
/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.)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.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./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.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.O_DIRECT took unlimited and under io.max 254:0 rbps=20000000. Nothing fails: the reads simply take longer.src/raw/cgroup.txt. Note dash's built-in echo reports any write error as "I/O error"; /bin/echo shows the real one.
pids.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.io.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).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.
--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.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
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.
| File | What happens at the boundary |
|---|---|
memory.max | the wall: "If a cgroup's memory usage reaches this limit and can't be reduced, the OOM killer is invoked in the cgroup" |
memory.high | the 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.max | how much of the group may be swapped out (0: none, so anonymous memory cannot be reclaimed at all) |
memory.min, memory.low | protection: 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 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:
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.oom_kill 1). Fast, loud, unambiguous.memory.high=200M, no swap, no memory.max: the same full-speed steps up to 190 MiB.memory.events counted high events and no OOM. To the outside it looks hung, with no error anywhere.memory.high=200M with swap allowed: full speed up to 190 MiB, as before.memory.current stays at 199 MiB while the process holds 300 (the purple part is swapped out), each step still a few tens of milliseconds.pgmajfault already).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.group | worker | main | memory.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.
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.
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).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).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).
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?memory.high the kernel reclaims and then makes the task sleep, up to 2 s per return to user space, for as long as the overage lasts. With no swap and mostly anonymous memory there is nothing to reclaim, so it never gets back under: the "memory.high, no swap" run above stopped progressing after 210 MiB. Use memory.high only with something watching it (PSI, a controller that raises it), or not at all.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).
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.
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.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).nice -5 for a data-feeding process failed without CAP_SYS_NICE.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.
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)).
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.
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
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.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.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".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.getppid took ns with no filter and ns under Docker's; eight more trivial filters, all of which run, made it ns.io_uring_enter, never the operations inside. Docker 25 therefore blocks io_uring_setup itself (EPERM, below)./* 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 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):
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.
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 (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.
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.
--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.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).
/etc/shadow but allow every other openat. Can it?args[1]. Even if it could read the string, another thread could change it after the check (a time-of-check to time-of-use race). USER_NOTIF and TRACE hand the decision to another process, which has the same race to handle. Path policies belong to LSMs such as AppArmor, SELinux or Landlock, which check the resolved file inside the kernel.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.
| Module | Policy is about | Where you meet it |
|---|---|---|
| AppArmor | paths: per-program profiles listing which files, capabilities and network access are allowed | Ubuntu 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 |
| SELinux | labels: every process and file carries a type, and a policy says which types may act on which | RHEL, 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) |
| Landlock | unprivileged 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.
:z or :Z option so the runtime relabels it. ausearch -m avc (SELinux) or dmesg | grep apparmor on the host shows the denial.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).
psThe 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.
"live-restore": true in the daemon configuration, containers keep running under their shims while dockerd restarts (Docker docs).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.
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
/sbin/init and "memory overhead <= 5 MiB" per VM.| What the untrusted code talks to | What protects the host | Cost | |
|---|---|---|---|
| Container (runc) | the host kernel, about 340 allowed calls | namespaces, cgroups, capabilities, seccomp, LSM | none 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 space | the 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 microVM | a 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 Containers | a guest kernel in a lightweight VM, managed as a container through containerd | hardware 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.
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).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).
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.
libcuda.so (copied from a build machine) shadows the host's and fails on a different driver version. Never put driver libraries in images.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.
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 write | The kubelet computes | The 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 it | cpu.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.cpu | quota = milli × period / 1000 with period 100,000 us, at least 1,000 us (MilliCPUToQuota, line 61) | cpu.max = "quota 100000" |
limits.memory | bytes | memory.max; plus memory.oom.group=1 on cgroup v2 (section 5) |
requests.memory | used 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 whole | QoS 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 class | Guaranteed -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 (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/...).
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.requests.cpu: 4, limits.cpu: 4, requests.memory: 32Gi and no memory limit. Its QoS class?memory.max (it can use the whole node), and an oom_score_adj of 1000 - 1000 × 32 GiB / node memory. Check it in the calculator above (preset "memory request only" is the same shape).| Symptom | Cause | Check | Fix |
|---|---|---|---|
docker stop or a pod deletion loses the last checkpoint; exit 143 at once | a 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 1 | exec python, exec-form CMD, or a forwarding trap |
| Stop takes exactly the grace period, then exit 137 | PID 1 has no SIGTERM handler and ignores it (2) | grep SigCgt /proc/1/status | handle SIGTERM, or --init with Python as its direct child |
Exit 137, OOMKilled, all workers gone at once | memory.max reached; on Kubernetes memory.oom.group=1 kills the whole container (5) | memory.events, kubectl describe pod | raise the limit to the measured peak, cut workers or prefetch |
| Job stops progressing, no error, no OOM | over memory.high with nothing reclaimable (5) | memory.events high count rising; memory.pressure where PSI exists | remove or raise memory.high |
| "can't fork" or "can't start new thread" with plenty of memory | pids.max counts threads (4) | pids.current, pids.events | raise the pids limit; cap OpenMP threads per worker |
| Bus error or "No space left on device" in DataLoader workers | 64 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 memory | 64 KiB RLIMIT_MEMLOCK (6) | ulimit -l | --ulimit memlock=-1 or CAP_IPC_LOCK |
EPERM from perf, io_uring, unshare, mount | seccomp profile or a missing capability (6, 7) | grep -E 'Cap|Seccomp' /proc/self/status | add the one capability or a custom profile; never --privileged |
io_uring ENOMEM on an older kernel with plenty of memory | the UID's locked-memory budget is shared across containers (7) | same call as another UID | a 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 fills | overlayfs copy-up into the writable layer (3) | docker diff, df -h / | write data and checkpoints to volumes |
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.docker stop, and sometimes die instantly without checkpointing?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.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.cpu.weight does it get, and why might that differ between clusters?Links checked on 5 October 2026; page times updated 24 October 2026. Times are estimates for the part worth reading. Suggested order: the Reading tab, stepping section 0 before sections 1 to 7; Julia Evans' zine for intuition; then the kernel's cgroup v2 document and the man pages for whatever you are debugging.
Section 8 is the intuition for this page: the four restrictions read from inside one container. The running training job is followed through the whole OS.
On the root page, the container cases: "Killed with exit code 137: the cgroup OOM killer", "DataLoader workers run out of /dev/shm", "Step time quadruples under a CPU limit: cgroup throttling", "Too many threads for the CPUs you have", "BlockingIOError on fork: the pids limit counts threads too", "Zombies pile up when the training script is PID 1", "docker stop takes 10 s and ends in 137: SIGTERM ignored by PID 1".
On the root page: the job's SIGTERM path traced call by call.
task_struct, fork and exec, zombies and orphans, PID 1's duties, signals in depth, and the Shutdown lab that first measured the tini and shell trap.
How the scheduler enforces cpu.weight and cpu.max, throttling measured, and the shares-to-weight conversion measured on this VM.
The OOM killer and its score, memory cgroup files, swap, pinned memory and mlock.
Why a job's memory.current grows: arenas, fragmentation, PyTorch's caching allocator.
io_uring and epoll in depth, the calls Docker 25 now blocks.
Writeback charged to cgroups, durable checkpoints on volumes, network and parallel file systems.
Hypervisors and KVM, the IOMMU and passthrough, MIG, and one CUDA call down to the driver: what a microVM sandbox and a GPU container stand on.
Kubernetes and Slurm for ML: GPU scheduling, gang scheduling, queues; this page's section 12 is what happens on the node.
The control loop, device plugins, the GPU Operator, gang scheduling: Kubernetes as a system, above the node-level files of section 12.
Sandboxing as one defence among permissions, egress control and approval: the security design that section 10's gVisor and microVMs serve.
Code-execution sandboxes for agents, where section 10's gVisor and microVMs are used.
Checkpoint and restart, spares and elastic training around the stop path of section 2.
torchrun, elastic launch and NCCL, which need the host network, shared memory and locked memory discussed here.
Sockets and interfaces, what a network namespace makes private.
The intuition for every piece on this page, drawn.
The reference for every cgroup file; read "Delegation" and the memory section's "Usage Guidelines".
Michael Kerrisk's man pages, with example programs.
Seven articles that build each namespace with small C programs, like the Build tab.
Actions, return values, user notification.
What config.json and an image manifest contain.
Requests, limits and their meaning, from the user's side.
Two answers to "what if the code inside is hostile".
Processes and security, the book chapters this page builds on.