IN·80
Containers
What a container really is: ordinary Linux processes isolated with namespaces, limited with cgroup v2, and confined with capabilities, seccomp and LSMs, running on a filesystem assembled from image layers by overlayfs. Covers containers versus virtual machines (and microVMs, gVisor, Kata, Wasm), each namespace type, cgroup controllers, the OCI image, runtime and distribution specs, content-addressed layers and digests, registries, the runtime stack (runc/crun, containerd, CRI-O, Podman), rootless containers, volumes, and container networking from veth pairs and bridges to overlays and CNI.
Start here: a container, built by hand
Two kernel features make a container
A container is not a small virtual machine. It's an ordinary Linux process that the kernel treats specially in two ways:
- Namespaces change what the process can see: its own process tree (PID namespace), hostname (UTS), filesystem mounts (mount), network interfaces (net), IPC objects, user IDs (user) and cgroup tree (cgroup).
- Control groups (cgroups) change what the process can use: memory, CPU time, I/O bandwidth, number of processes.
Add a separate root filesystem (the files from an image) and you have the core of every container runtime. Let's do it with standard tools:
$ hostname; echo $$; ls / | head -3
vm
31184
bin
bin.usr-is-merged
boot
$ unshare --pid --fork --uts --mount --mount-proc=rootfs/proc chroot rootfs /bin/sh -c "hostname tiffin-box; hostname; ps; ls /"
tiffin-box
PID USER TIME COMMAND
1 root 0:00 /bin/sh -c hostname tiffin-box; hostname; ps; ls / | head -5 | tr "\n" " "; echo; cat /etc/os-release | head -1
4 root 0:00 ps
bin dev etc home lib
NAME="Alpine Linux"
$ hostname # back on the host: unchanged
vm
Inside, the shell was PID 1, ps showed only two processes, the hostname change didn't leak out, and / was Alpine's files, not Ubuntu's. Yet it was running on the same kernel, started in a few milliseconds, and the host could see it as a normal process all along.
Limits with a cgroup
Now limits. Create a memory cgroup, set 32 MB, put a process in it, and let the process try to allocate 400 MB:
mkdir -p /sys/fs/cgroup/memory/tiffin-demo
echo $((32*1024*1024)) > /sys/fs/cgroup/memory/tiffin-demo/memory.limit_in_bytes
sh -c 'echo $$ > /sys/fs/cgroup/memory/tiffin-demo/cgroup.procs; exec python3 -c "…allocate 100 × 4 MB…"'
exit status: 137 (137 = killed by SIGKILL)
times the limit was hit: 39; OOM kills: 1
The kernel let the process reach its limit, tried to reclaim memory 39 times, then the OOM killer ended it, without Python ever seeing a MemoryError. Docker's --memory 64m and Kubernetes' resources.limits.memory do exactly this. CPU limits work through the same mechanism, using the CPU controller's quota and period (lab experiment 3).
Images and runtimes
A real container runtime adds the rest: an image (a stack of read-only filesystem layers plus metadata such as the command to run, environment and user), a writable layer on top (overlayfs), a network namespace wired to the host with a virtual Ethernet pair, security settings (dropped capabilities, seccomp syscall filtering, AppArmor/SELinux, no-new-privileges), and an API. The stack in Docker and Kubernetes is: Docker / kubelet → containerd → runc → the kernel. runc's job is precisely what we did by hand: create namespaces, set up cgroups, pivot to the root filesystem and exec the program. These pieces are standardised by the Open Container Initiative (OCI): the image format, the runtime specification and the distribution (registry) protocol.
| Virtual machine | Container | |
|---|---|---|
| Kernel | Its own guest kernel | Shares the host kernel |
| Start time | Seconds to minutes (boots an OS) | Milliseconds to a second |
| Isolation boundary | Hardware virtualisation (hypervisor) | Kernel namespaces, cgroups, seccomp, LSMs |
| Overhead | A whole OS per instance | Roughly that of a process |
| Strongest use | Untrusted or different-OS workloads | Packaging and running your own services densely |
Sandboxed runtimes (gVisor, Kata Containers, Firecracker microVMs) sit in between, giving container ergonomics with VM-like isolation.
How deep to go in containers
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain containers versus VMs, images, and namespaces and cgroups by name |
| L2 | Run containers with limits, users, volumes and ports; read their logs and status |
| L3 | Explain each namespace, cgroup controllers (v1 and v2), overlayfs, OCI and the runtime stack |
| L4 | Diagnose OOM kills, CPU throttling, permission and mount problems, runtime memory sizing |
| L5 | Choose runtimes, isolation levels, base images and security profiles for a platform |
| L6 | Operate runtimes at fleet scale: cgroup v2 migration, rootless, sandboxing and policy enforcement |
Containers versus virtual machines
Two kinds of isolation
A virtual machine emulates hardware: a hypervisor (KVM, Xen, Hyper-V, ESXi, Firecracker) runs several guest kernels, each believing it owns a computer. A container is a set of ordinary processes on the host kernel, given a restricted view of the system (namespaces), restricted resources (cgroups) and restricted privileges (capabilities, seccomp, LSMs).
| Virtual machine | Container | |
|---|---|---|
| Isolation boundary | Hardware virtualisation (CPU VT-x/AMD-V, separate kernels) | Kernel features on a shared kernel |
| Start time | Seconds to minutes (microVMs: ~100 ms) | Milliseconds (it's fork/exec plus setup) |
| Overhead | A whole guest OS per VM (memory, boot) | Near zero: a process with a different view |
| Image size | GBs (full OS disk) | MBs (app + userland libraries; can be one static binary) |
| Kernel | Any guest OS (Windows on Linux host) | Must use the host kernel: Linux containers need a Linux kernel (Docker Desktop runs a Linux VM on macOS/Windows) |
| Security | Strong boundary; hypervisor escapes are rare | A kernel bug can let a container escape to the host; defence in depth needed |
| Density | Tens per host | Hundreds to thousands per host |
In between: sandboxed containers and microVMs
When you need container ergonomics with stronger isolation (multi-tenant platforms, untrusted code):
- gVisor (Google): a user-space kernel (Sentry) intercepts the container's syscalls, so the host kernel exposes a much smaller surface. Used by Cloud Run (first generation), GKE Sandbox.
- Kata Containers: each pod runs in a lightweight VM with its own kernel, behind the same container interfaces (CRI).
- Firecracker (AWS): minimal KVM-based microVMs (~125 ms boot, ~5 MB overhead) behind Lambda and Fargate.
- WebAssembly runtimes (Wasmtime, WasmEdge, Spin; containerd "runwasi" shims) run Wasm modules with capability-based sandboxing and very fast start, for workloads that can compile to Wasm (Rust, Zig, C, Go/TinyGo, increasingly others).
Namespaces: what a process can see
A namespace wraps a global system resource so processes inside it see their own isolated instance. A process is in exactly one namespace of each type; children inherit them. Created with clone(CLONE_NEW…), unshare(), joined with setns(). See them in /proc/<pid>/ns/ or with lsns.
| Namespace | Flag | Isolates | Effect in a container |
|---|---|---|---|
| PID | CLONE_NEWPID |
Process IDs | Container's first process is PID 1; it can't see host processes |
| Mount | CLONE_NEWNS |
Mount table | Own root filesystem (via pivot_root), own mounts |
| Network | CLONE_NEWNET |
Interfaces, IPs, routes, ports, firewall rules | Own eth0, own localhost, own port 8080 |
| UTS | CLONE_NEWUTS |
Hostname, domain name | Own hostname |
| IPC | CLONE_NEWIPC |
System V IPC, POSIX message queues | No shared memory with host processes |
| User | CLONE_NEWUSER |
UID/GID mappings, capabilities | Root inside maps to an unprivileged UID outside (rootless containers, Kubernetes user namespaces, GA in 1.36) |
| Cgroup | CLONE_NEWCGROUP |
View of the cgroup hierarchy | Container sees its cgroup as the root |
| Time | CLONE_NEWTIME |
CLOCK_MONOTONIC/BOOTTIME offsets |
Checkpoint/restore (CRIU) across hosts |
Sharing namespaces is how Kubernetes pods work: all containers in a pod share the network namespace (they talk over localhost, share ports) and optionally the PID namespace, while having separate mount namespaces (chapter 83).
You can build a "container" with nothing but util-linux:
# A shell in new PID, mount, UTS, IPC and network namespaces, with its own /proc
sudo unshare --pid --fork --mount-proc --uts --ipc --net bash
hostname sandbox && hostname # changes only inside
ps aux # only bash and ps: we are PID 1
ip link # only a downed loopback interface
# Rootless: an unprivileged user namespace where you appear as root
unshare --user --map-root-user bash -c 'id' # uid=0(root) … but only inside
// Go: the heart of a toy container runtime, re-exec ourselves in new namespaces
func main() {
switch os.Args[1] {
case "run":
cmd := exec.Command("/proc/self/exe", append([]string{"child"}, os.Args[2:]...)...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS |
syscall.CLONE_NEWNET | syscall.CLONE_NEWIPC,
Unshareflags: syscall.CLONE_NEWNS, // don't propagate mounts back to the host
}
must(cmd.Run())
case "child":
must(syscall.Sethostname([]byte("container")))
must(syscall.Chroot("/var/lib/toy/rootfs")) // real runtimes use pivot_root
must(os.Chdir("/"))
must(syscall.Mount("proc", "/proc", "proc", 0, ""))
must(syscall.Exec(os.Args[2], os.Args[2:], os.Environ()))
}
}
// C: clone() with namespace flags; the child starts in fresh PID and UTS namespaces
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
static char stack[1 << 20];
static int child(void *arg) {
sethostname("container", 9);
printf("child sees itself as PID %d\n", getpid()); // prints 1
execlp("/bin/sh", "sh", NULL);
return 1;
}
int main(void) {
pid_t pid = clone(child, stack + sizeof stack, CLONE_NEWPID | CLONE_NEWUTS | SIGCHLD, NULL);
waitpid(pid, NULL, 0);
}
// Rust (nix crate): unshare namespaces, then fork so the child becomes PID 1 in the new PID ns
use nix::sched::{unshare, CloneFlags};
use nix::unistd::{fork, ForkResult, sethostname, execvp};
use std::ffi::CString;
unshare(CloneFlags::CLONE_NEWUTS | CloneFlags::CLONE_NEWPID | CloneFlags::CLONE_NEWNS)?;
match unsafe { fork()? } {
ForkResult::Child => {
sethostname("container")?;
let sh = CString::new("/bin/sh")?;
execvp(&sh, &[&sh])?;
}
ForkResult::Parent { child } => { nix::sys::wait::waitpid(child, None)?; }
}
Those few dozen lines show the essential idea: a container is a process started with different namespaces. Real runtimes add the rootfs from image layers, cgroups, capabilities, seccomp, user mappings, networking and much more, following the OCI runtime spec.
cgroups: what a process can use
cgroup v2
Control groups organise processes into a hierarchy and apply resource accounting and limits per group. Modern distributions and Kubernetes use the unified cgroup v2 hierarchy, mounted at /sys/fs/cgroup. (cgroup v1 had separate hierarchies per controller and is deprecated; Kubernetes moved v1 support into maintenance mode and newer releases expect v2.)
Each cgroup is a directory; you control it by writing files:
| Controller | Key files | Effect |
|---|---|---|
| cpu | cpu.max (quota period, e.g. 50000 100000 = 0.5 CPU), cpu.weight (relative share, default 100) |
Quota caps CPU time per period (throttling); weight divides contended CPU proportionally |
| cpuset | cpuset.cpus, cpuset.mems |
Pin to specific CPUs / NUMA nodes |
| memory | memory.max (hard limit → OOM kill), memory.high (throttle and reclaim above it), memory.min/low (protection), memory.swap.max |
Limits and protects memory, including page cache charged to the group |
| io | io.max (rbps, wbps, riops, wiops per device), io.weight |
Disk bandwidth and IOPS |
| pids | pids.max |
Caps number of processes/threads (fork-bomb protection) |
Monitoring files: cpu.stat (usage, nr_throttled, throttled_usec), memory.current, memory.stat, memory.events (oom_kill count), io.stat, *.pressure (PSI per cgroup).
# Create a cgroup, cap it at half a CPU and 256 MiB, and move a shell into it
sudo mkdir /sys/fs/cgroup/demo
echo "+cpu +memory +pids" | sudo tee /sys/fs/cgroup/cgroup.subtree_control
echo "50000 100000" | sudo tee /sys/fs/cgroup/demo/cpu.max
echo $((256*1024*1024)) | sudo tee /sys/fs/cgroup/demo/memory.max
echo 100 | sudo tee /sys/fs/cgroup/demo/pids.max
echo $$ | sudo tee /sys/fs/cgroup/demo/cgroup.procs
cat /sys/fs/cgroup/demo/cpu.stat # watch nr_throttled grow under load
# Or let systemd do it: systemd-run --scope -p CPUQuota=50% -p MemoryMax=256M ./app
How limits feel to applications
- CPU quota is enforced per period (default 100 ms): a container with
cpu.max = 100000 100000(1 CPU) running 4 busy threads uses its 100 ms of quota in 25 ms of wall time, then stalls for 75 ms. Average CPU looks fine while p99 latency suffers. This is CPU throttling, the reason many teams set CPU requests but not limits in Kubernetes (chapter 83). - Runtimes must notice the limits: the JVM, Go (since 1.25 for
GOMAXPROCS), .NET and recent Node read cgroup files to size thread pools and heaps. Old runtimes see the host's 64 cores and 256 GB and size themselves accordingly, then get throttled or OOM-killed. Python'sos.cpu_count()returns host CPUs, andos.process_cpu_count()(3.13+) respects CPU affinity but not quotas, so derive worker counts fromcpu.maxor configuration. - Memory limit includes page cache charged to the group; the kernel reclaims cache first, then OOM-kills if anonymous memory exceeds
memory.max. Container exit code 137 usually means this.
Other confinement layers
Namespaces and cgroups don't stop a process from calling dangerous syscalls on the shared kernel. Runtimes add:
- Capabilities: containers start with a reduced default set (Docker's default keeps about 14, such as
CHOWN,NET_BIND_SERVICE,SETUID; it dropsSYS_ADMIN,NET_ADMIN,SYS_PTRACE,SYS_MODULE). Best practice:--cap-drop=ALLand add back only what's needed. - seccomp: a BPF filter allowing or denying syscalls. Docker's and containerd's default profile blocks about 40–60 risky syscalls (
kexec_load,open_by_handle_at,bpf,mountwithout caps…). Kubernetes:seccompProfile: RuntimeDefault. - LSMs: AppArmor or SELinux profiles confine container processes (Docker's
docker-defaultAppArmor profile; SELinuxcontainer_twith per-container MCS labels). no_new_privs: setuid binaries can't gain privileges (--security-opt no-new-privileges).- Read-only root filesystem, non-root users, and user namespaces (root in the container is nobody on the host).
- "Privileged" containers (
--privileged) turn most of this off: all capabilities, all devices, no seccomp. Treat them as root on the host.
Images
What an image is
A container image is a packaged filesystem plus metadata, standardised by the OCI Image Specification:
- Layers: tar archives (usually gzip or zstd compressed), each a filesystem diff (added, changed and deleted files, deletions recorded as "whiteout" files).
- Config (JSON): default command (
Entrypoint,Cmd), environment, working directory, user, exposed ports, labels, and the ordered list of layer diff IDs, plus history. - Manifest (JSON): references the config and the layers by digest and size.
- Image index (manifest list): maps platforms (
linux/amd64,linux/arm64) to platform-specific manifests, so one tag serves many architectures.
Everything is content-addressed: a digest is sha256: of the exact bytes. Change one byte and the digest changes. So a manifest digest uniquely and immutably identifies an image, and pulling by digest guarantees you get exactly what you tested.
Layers and overlayfs
At runtime, the image's layers are stacked with overlayfs:
- The image layers are the read-only lower directories.
- Each container gets a thin writable upper directory.
- Reads find a file in the topmost layer that has it; writes trigger copy-up (the file is copied from the lower layer to the upper, then modified); deletes create whiteouts.
Consequences:
- Layers are shared between images and containers on a host: ten containers of the same image cost one copy of the image plus ten small upper dirs.
- Writes to the container filesystem are slow for large files (copy-up), ephemeral (lost when the container is removed), and invisible to other containers. Put data in volumes.
- Deleting a file in a later layer doesn't shrink the image: the bytes still exist in the earlier layer. Remove caches in the same layer that created them (chapter 81). Secrets added in one layer and deleted in the next are still extractable.
Tags versus digests
- A tag (
orders:1.4,latest) is a mutable pointer in a repository; it can be moved to a different image at any time. - A digest (
orders@sha256:a1…) is immutable. - Best practice: build once, tag with something meaningful (Git SHA, semantic version), and deploy by digest (or pin both:
orders:1.4@sha256:…). Never deploylatestto production: you can't tell what's running or roll back precisely.
Registries
A registry stores and serves images over HTTP following the OCI Distribution Specification: GET /v2/<name>/manifests/<ref>, GET /v2/<name>/blobs/<digest>, chunked uploads, and a referrers API for attaching artifacts (signatures, SBOMs, attestations) to images.
- Public: Docker Hub (rate-limits anonymous pulls), GitHub Container Registry (ghcr.io), Quay.io, Amazon ECR Public, Google's mirror (
mirror.gcr.io). - Private/managed: Amazon ECR, Google Artifact Registry, Azure Container Registry, GitLab, JFrog Artifactory, Harbor (CNCF, self-hosted, with scanning, replication and signing policies), Zot.
- OCI artifacts: registries now store more than images: Helm charts, WASM modules, signatures (Sigstore/cosign, Notation), SBOMs, even ML models.
Operational concerns: pull-through caches / mirrors (avoid rate limits and outages of public registries), image retention policies (registries fill up), immutable tags settings (forbid re-pushing a tag), vulnerability scanning on push, authentication (credential helpers, workload identity), and replication across regions.
The runtime stack
"Docker" is several layers, mostly standardised and swappable:
- OCI runtime (low level): takes a bundle (root filesystem +
config.json) and creates the process: runc (Go, reference implementation), crun (C, faster, lower memory, default in Podman on Fedora/RHEL), youki (Rust), runsc (gVisor), kata-runtime. - containerd (CNCF graduated): image pull and storage, snapshotters (overlayfs, stargz lazy pulling), container lifecycle via per-container shims (so containers survive daemon restarts). The default runtime under Docker, most managed Kubernetes services, and nerdctl.
- CRI-O: a Kubernetes-only runtime implementing the Container Runtime Interface (OpenShift's default).
- Docker Engine (
dockerd): the developer-facing API with builds, networks, volumes, Compose; uses containerd underneath. Kubernetes removed its "dockershim" in 1.24, but images built with Docker run everywhere because they're OCI images. - Podman: daemonless, rootless by default, Docker-compatible CLI (
alias docker=podman), pods, generates Kubernetes YAML and systemd units ("Quadlet").
Rootless containers
Rootless mode runs the entire runtime as an unprivileged user using user namespaces (with subordinate UID ranges in /etc/subuid), slirp4netns or pasta for networking, and fuse-overlayfs or native rootless overlay. A container escape lands as an unprivileged user. Limitations: binding ports below 1024 needs configuration, some storage drivers and network modes are unavailable, and there may be slight performance costs. Podman is rootless by default; Docker supports a rootless mode.
Volumes and storage
Container filesystems are ephemeral. For data that must outlive a container, mount storage in:
| Kind | What | Use |
|---|---|---|
| Named volume | Managed by the runtime (/var/lib/docker/volumes/…), outside the overlay |
Databases in dev, persistent app data on one host |
| Bind mount | Host directory mounted into the container | Source code during development, config files; couples to the host layout and UIDs |
| tmpfs mount | RAM-backed | Scratch space, secrets that mustn't touch disk |
| Volume plugins / CSI | Network or cloud storage (EBS, NFS, Ceph) | Orchestrated persistent storage (Kubernetes PVs, chapter 83) |
Permission pitfalls: files in volumes keep numeric UIDs. A container running as UID 10001 can't write to a bind-mounted directory owned by host UID 1000. Fix with matching UIDs, chown in an init step, group permissions (fsGroup in Kubernetes), or user-namespace ID mapping (idmapped mounts).
Container networking
Single-host networking
Each container usually gets its own network namespace. The runtime connects it to the host:
Modes (Docker terms; Podman similar):
- bridge (default): veth pairs to a Linux bridge, private subnet, NAT outbound, published ports (
-p 8080:80) via DNAT. User-defined bridge networks add an embedded DNS server so containers resolve each other by name, which the default bridge doesn't do. - host: the container shares the host's network namespace: no isolation, no NAT, best performance.
- none: only loopback.
container:<id>: join another container's network namespace (the pattern Kubernetes pods use).- macvlan / ipvlan: containers get addresses on the physical network.
- overlay: VXLAN tunnels connect containers across hosts (Docker Swarm; Kubernetes CNI plugins like Flannel).
Multi-host networking and CNI
Kubernetes requires that every pod can reach every other pod by IP without NAT. The Container Network Interface (CNI) is the plugin standard that sets up a pod's network namespace. Implementations:
- Overlay (VXLAN/Geneve encapsulation): Flannel, Calico in VXLAN mode.
- Routed (BGP or cloud routes, no encapsulation): Calico BGP, cloud-native CNIs (AWS VPC CNI gives pods real VPC IPs; Azure CNI; GKE's VPC-native).
- eBPF dataplanes: Cilium (CNCF graduated) implements routing, load balancing (replacing kube-proxy), network policy, encryption and observability (Hubble) in eBPF programs in the kernel.
Chapter 83 covers Services, DNS and network policies on top of this.
Language runtimes in containers
The best image depends on how your language ships:
| Language | Typical runtime needs | Smallest practical base |
|---|---|---|
| Go | Static binary (with CGO_ENABLED=0) |
scratch or gcr.io/distroless/static (add CA certificates and timezone data if needed) |
| Rust | Static with musl target, or dynamic against glibc | scratch/distroless static (musl) or distroless cc (glibc) |
| Zig, C, C++ | Static linking possible (Zig makes it easy, including cross-compiling to musl) | scratch / distroless static |
| Java / Kotlin | A JRE (or jlink-built custom runtime), or a GraalVM native image (static-ish binary) |
distroless java, Eclipse Temurin JRE, Chainguard/Wolfi JRE; or a jlink image of ~60–80 MB |
| Python | Interpreter + site-packages + native libraries | python:3.x-slim or distroless/Chainguard Python; beware Alpine/musl with prebuilt wheels |
| Node.js | Runtime + node_modules |
node:xx-slim, distroless nodejs |
| .NET | Runtime, or self-contained / Native AOT | mcr.microsoft.com/dotnet/runtime-deps (chiseled Ubuntu) |
Chapter 81 turns this into Dockerfiles.
Lab: inside containers, measured
Docker 29 (containerd, runc) on the volume's Ubuntu VM with cgroup v1, the tiffin:1.0 image (a static Go binary in a FROM scratch image) and an Alpine 3.22 base image built locally from its minirootfs.
Experiment 1: a container is a process, with its own namespaces
host PID of the container's 'PID 1': 994 (tiffin, uid 1000)
pid host pid:[4026531836] container pid:[4026532267]
net host net:[4026531833] container net:[4026532268]
mnt host mnt:[4026531832] container mnt:[4026532264]
uts host uts:[4026531838] container uts:[4026532265]
ipc host ipc:[4026531839] container ipc:[4026532266]
user host user:[4026531837] container user:[4026531837]
cgroup host cgroup:[4026531835] container cgroup:[4026531835]
The container's PID 1 was host PID 994, visible to ps, top and kill like any process. It had its own PID, network, mount, UTS and IPC namespaces, but shared the host's user namespace: uid 1000 inside is uid 1000 on the host, and uid 0 inside would be real root on the host (with capabilities trimmed). Docker only uses user namespaces with userns-remap or in rootless mode; Kubernetes added hostUsers: false for pods. On this cgroup v1 host the cgroup namespace was shared too (on cgroup v2, Docker gives each container its own by default).
Experiment 2: what starting a container costs
20 runs each:
plain process (fork + exec): 1.4 ms each
unshare + chroot (namespaces by hand): 3.4 ms each
docker run --rm (image, overlay, cgroups, network): 329 ms each
The kernel parts are cheap: namespaces added about 2 ms. Docker's 330 ms went on the API round trips, preparing the overlay filesystem, creating cgroups, setting up a network namespace with a veth pair and iptables rules, starting the shim and tearing it all down. Still far below a VM boot, which is why containers suit autoscaling and per-test environments; for millisecond-scale isolation (functions, sandboxes) people use pre-warmed pools or microVM snapshots.
Experiment 3: CPU limits are quotas
A busy loop in a container with --cpus 0.5, for 10 seconds:
docker stats: CPU 49.54%
cpu.cfs_quota_us=50000 cpu.cfs_period_us=100000; nr_periods 112 nr_throttled 111
--cpus 0.5 became a CFS quota of 50 ms of CPU per 100 ms period. The loop used its 50 ms early in each period and was then throttled for the rest: 111 of 112 periods. For a web server, throttling shows up as latency spikes of up to tens of milliseconds even though average CPU looks fine, which is why many teams set CPU requests in Kubernetes but no CPU limit for latency-sensitive services (chapter 83), and watch nr_throttled.
Experiment 4: does the runtime know about the limit?
JDK 21's default maximum heap, outside and inside a 256 MB memory cgroup:
on the host: MaxHeapSize 1496 MB
in the 256 MB cgroup: MaxHeapSize 126 MB
same, -XX:MaxRAMPercentage=75: MaxHeapSize 192 MB
Modern JVMs read the cgroup limit (this VM itself sits in a 5.84 GB cgroup, so "the host" got a quarter of that). With small limits the JVM defaults to half the memory as heap, leaving the rest for metaspace, thread stacks, code cache and native buffers; MaxRAMPercentage=75 is a common setting for containers with 512 MB or more. Other runtimes need explicit help: Node's heap ignores cgroup limits in older versions (--max-old-space-size), Go 1.19+ honours GOMEMLIMIT only if you set it, and Python has no heap limit at all. Always set the runtime's limit below the container's, or the OOM killer, not your runtime, decides when to stop.
Experiment 5: copy-on-write layers
A container adds a file, deletes /etc/motd, and writes /tmp/x:
C /etc
A /etc/hosts.new
D /etc/motd
C /tmp
A /tmp/x
The image layers stayed read-only; the container's changes went to its own writable layer (A = added, D = deleted, recorded as a "whiteout", C = changed directory). They disappear when the container is removed, which is why data belongs in volumes, and why writing heavily inside the container filesystem (logs, caches) is slow and wasteful.
Experiment 6: user namespaces
An unprivileged user (meena, uid 30033) creates a user namespace:
uid=0(root) gid=0(root) groups=0(root)
touch: cannot touch '/etc/test': Permission denied
0 30033 1
Inside, she's root (uid 0), with full capabilities over the namespace's own resources, but uid_map shows inside-0 maps to outside-30033, so the host's files still see an ordinary user and refused the write. This is how rootless Podman and Docker, and Kubernetes user-namespaced pods, run "root" containers without host root.
Try it yourself
- Repeat experiment 3 with
--cpus 1.5and a 3-thread busy loop. What arequotaandnr_throttled? - Run
docker run --rm --cap-drop ALL --read-only --security-opt no-new-privileges tiffin:1.0and confirm it still works. - Find a container's cgroup directory from its PID via
/proc/PID/cgroupand readmemory.usage_in_bytesandmemory.stat. - Enter a running container's namespaces from the host with
nsenter -t PID -n ss -tlnand explain the output.
Revision sheet: containers
Key ideas
- Container vs VM: shared kernel, process-level overhead, kernel-enforced isolation vs hypervisor isolation; sandboxed runtimes in between.
- Namespaces: pid, net, mnt, uts, ipc, user, cgroup, time.
- cgroups: v1 (controller hierarchies) vs v2 (unified,
memory.max,cpu.max, PSI); memory (limit, OOM), CPU (shares/weight, quota/period), pids, io. - Confinement: capabilities, seccomp, AppArmor/SELinux, read-only root, no-new-privileges, rootless and user namespaces.
- Images: layers, manifests, config, digests, multi-arch indexes; OCI image spec.
- Registries: OCI distribution API, tags vs digests, mirrors and pull-through caches.
- Runtime stack: CLI/kubelet → containerd/CRI-O → shim → runc/crun → kernel; CRI.
- Storage: overlayfs copy-on-write, volumes, bind mounts, tmpfs.
- Networking: veth pairs, bridges, NAT and port publishing, host and none modes, CNI.
- Runtimes in containers: memory sizing (JVM, Node, Go, Python), CPU counts, PID 1 signal handling and zombie reaping (tini).
Numbers to remember
--cpus 0.5= quota 50 ms per 100 ms period.- Lab: namespaces cost ~2 ms;
docker run --rm~330 ms; a 0.5-CPU busy loop was throttled in 111/112 periods; JVM default heap was 126 MB in a 256 MB cgroup (192 MB at MaxRAMPercentage=75).
Pitfalls
- Treating containers as a security boundary for untrusted code.
- Running as root inside without user namespaces.
- CPU limits on latency-sensitive services without watching throttling.
- Runtimes sized for the host, not the container.
- Writing data into the container's writable layer.
- A shell script as PID 1 that doesn't forward SIGTERM.
Glossary
- Namespace: kernel-provided isolated view of a resource type.
- cgroup: kernel resource accounting and limiting group.
- CFS quota: CPU time allowed per period for a cgroup.
- overlayfs: union filesystem merging read-only and writable layers.
- OCI: Open Container Initiative standards.
- Whiteout: marker hiding a lower-layer file deleted in an upper layer.