1. The same binary, two worlds: what petla.c actually measures
Conversations about containerization tend to swing between two blunt generalizations. The first says: “Docker is basically a lightweight virtual machine, so everything runs noticeably slower inside it.” The second swings to the opposite extreme: “containers have negligible overhead, so you can put anything in them for free.” Both claims are too coarse to design real systems around — so here I look beneath the abstraction into the Linux kernel and measure where overhead actually arises. (For a ground-up Docker walkthrough and deployment workflows, see the companion guide: Docker and Containers in Practice →.)
To see what really happens, I started with the simplest experiment capable of stripping away every confounding variable (different system C libraries glibc vs. musl, network setup, disk writes or daemon startup). I wrote a short C program, petla.c (Polish for “loop”), that runs 150 million sequentially dependent iterations of a xorshift64 generator and prints the resulting checksum alongside its internally measured elapsed time:
#define _POSIX_C_SOURCE 200809L
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
int main(void) {
struct timespec start, stop;
uint64_t x = 1;
clock_gettime(CLOCK_MONOTONIC, &start);
for (unsigned i = 0; i < 150000000; ++i) {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
}
clock_gettime(CLOCK_MONOTONIC, &stop);
double ms = (stop.tv_sec - start.tv_sec) * 1000.0
+ (stop.tv_nsec - start.tv_nsec) / 1e6;
printf("%016" PRIx64 " %.3f\n", x, ms);
}
Compiling with -O2 -static is a crucial methodological detail. Static linking guarantees that both the host and the Alpine container (whose own C library is musl) execute the exact same ELF executable, instruction for instruction. Printing the final value of x keeps the compiler from eliminating the loop and immediately confirms that both environments computed the exact same bit pattern.
New to Docker? Five terms in 30 seconds:
- Image: a read-only template holding a program and its libraries (built from a
Dockerfilerecipe or pulled from a registry, such asalpine).- Container: a disposable live run of that image; deleting a container removes its scratch space while the image stays intact.
- Bind mount & volume: attaching durable host storage outside the container (covered with a full
compose.yamlwalkthrough at the start of Docker and Containers in Practice).:ro/readonly: a kernel-enforced write lock (like the write-protect switch on an SD card).-p 127.0.0.1:8081:8080: forwarding traffic from a local host port into the container’s private network.Treat that strictly as a starting mental model: below, we will see there is no virtual “disc” or guest OS underneath — just an ordinary Linux process and four kernel mechanisms.
# Linux x86-64 (AMD Ryzen 5 7600), GCC 15.2.0, kernel 7.0.0-44-generic, Docker Engine 29.1.3
cc -std=c11 -O2 -static petla.c -o petla
# Pin the native process to logical core 4 (host equivalent of --cpuset-cpus=4)
taskset -c 4 ./petla
docker run --rm --pull=never --read-only --network none --cpuset-cpus=4 \
--mount "type=bind,src=$PWD/petla,dst=/petla,readonly" alpine /petla
The long list of flags above exists solely to keep the test conditions identical — passing our compiled ./petla binary read-only (--mount ...,readonly) into the minimal alpine image, disabling networking and writes, and pinning the process to the same CPU 4. Each flag is explained in the sections that follow. The Alpine image was already present locally (digest alpine@sha256:28bd5fe8b56d1bd048e5babf5b10710ebe0bae67db86916198a6eec434943f8b), both runs were pinned to the same logical core (CPU 4), and after one warm-up per variant I ran seven alternating pairs (pair 1: container host, pair 2: host container, and so on). The raw loop times (in milliseconds, in run order) were:
| Variant | 1 | 2 | 3 | 4 | 5 | 6 | 7 | Min [ms] | Median [ms] | Max [ms] |
|---|---|---|---|---|---|---|---|---|---|---|
| Host | 185.797 | 184.810 | 196.359 | 186.237 | 207.839 | 213.840 | 210.832 | 184.810 | 196.4 | 213.840 |
| Container | 184.484 | 206.996 | 188.985 | 187.201 | 187.837 | 213.507 | 209.945 | 184.484 | 189.0 | 213.507 |
Reading those numbers like an engineer yields two conclusions at once. First, we do not declare that “a container is 7 ms faster than the host.” Notice the bimodal shape in both rows: some runs cluster around 185–189 ms while others (especially trials 5–7) sit around 207–214 ms, reflecting normal CPU boost-frequency transitions, power states and background system noise. Pairwise differences swing slightly negative and slightly positive (the median Container − Host difference is just −0.89 ms, under 0.5% of loop duration), and the two ranges overlap almost completely.
Second — and this is the premise of the entire article — for pure CPU computation, native Linux container overhead sits below the measurement noise floor. The physical reason is straightforward: in both cases the processor core executes the exact same sequence of x86-64 instructions in the same unprivileged mode (ring 3), with no hypervisor layer and no binary translation in between.
If a tight CPU loop runs at full silicon speed, where does container overhead actually come from? The cleanest way to reason about it is to split total execution time into four components:
In petla.c, clock_gettime ran inside the binary, isolating alone. In real workloads, the other three terms — creating and tearing down the container (), traversing virtual networking and filtered syscalls (), and writing into a layered filesystem () — behave very differently. To see when they remain near zero and when they dominate the entire system, we need to examine the Linux kernel primitives underneath.
2. The OCI runtime stack and the “lightweight VM” myth
Informal descriptions often talk about “running Docker” as if Docker itself were a hypervisor or a miniature operating system. Inside the Linux kernel, there is no single object called a “container.” A container is a composition of independent kernel features configured by user-space tooling for one or more processes just before execve.
When you type docker run on Linux, a layered execution chain built on the open OCI (Open Container Initiative) specifications runs in the background:
docker(CLI) translates command-line flags into an HTTP request sent over a Unix socket to thedockerddaemon.dockerdmanages images, networks and volumes, delegating container execution tocontainerd.containerdprepares an unpacked filesystem snapshot (via a snapshotter, usuallyoverlayfs) and launches a small helper process,containerd-shim, which holdsstdin/stdout/stderropen and lets the daemons restart without killing running containers.runc(the default low-level OCI runtime) invokes the kernel interfaces —clone3/unshare,cgroupswrites,pivot_root,capabilitiesandseccompfilter setup — then executes the target program (/petla) and exits.
Once petla.c is running, neither Docker, nor containerd, nor runc sits on its instruction path. To the Linux scheduler, it is an ordinary entry in the process table that you can inspect from the host with ps or htop. Tools such as Podman and Kubernetes runtimes rely on the exact same kernel primitives and the exact same OCI image format. Docker is a convenient interface, not the underlying isolation mechanism.
A critical distinction: native Linux vs. Docker Desktop vs. a virtual machine
Many performance and compatibility debates derail because platforms get conflated. The fact that a container on Linux is an ordinary process without a VM does not mean Docker Desktop on Windows or macOS works the same way. Neither the Windows NT kernel nor macOS’s XNU kernel provides Linux namespaces, cgroups v2 or the Linux syscall ABI — so Docker Desktop first boots a hidden Linux virtual machine (via WSL 2 / Hyper-V on Windows or Apple Virtualization Framework on macOS) and creates containers sharing that single guest kernel inside that VM.
Putting all four real execution layers side by side clarifies their architectures and security boundaries:
| Execution layer | Kernel servicing syscalls | Isolation boundary | Typical CPU cost (tight loop) | Main sources of overhead |
|---|---|---|---|---|
| Native process (Linux) | Host kernel | UID/GID permissions, filesystem ACLs | Baseline () | No intermediate layer |
| Native container (Linux) | Same host kernel | Namespaces + cgroups v2 + capabilities + seccomp | Near (in noise floor) | Container startup, OverlayFS copy-up, virtual bridge/NAT, cgroup throttle |
| Docker Desktop (Windows / macOS) | One Linux kernel in hidden VM (shared by containers) | Host hypervisor + container primitives inside VM | Low for CPU inside VM | VM RAM footprint, file bridge (VirtioFS/9P), USB passthrough (USB/IP) |
| MicroVM (Firecracker) / full VM | Separate guest kernel per VM | Hardware CPU virtualization (VT-x / AMD-V / Arm EL2) | Modest virtualization cost | RAM overhead per guest kernel, emulated or paravirtualized I/O |
3. Pillar one: Namespaces — the illusion of a private machine
If a containerized process is just a host process, why does running ps aux inside it show only itself as PID 1, why does it see its own IP address 172.17.0.2, and why does / contain a completely different filesystem? That illusion comes from Linux kernel namespaces — a kernel mechanism that wraps global system resources so processes inside a namespace see their own isolated instance of them.
Modern Linux implements eight namespaces (the eighth, time, isolates monotonic and boot-time clock offsets); a standard OCI container relies primarily on the first six:
pid(process tree): the process inside getsPID 1, while on the host it carries an ordinary PID (say,PID 14822). The host can see the entire subtree from above, whereas a process inside cannot see or signal anything outside itspidnamespace.mnt(mount table): a private filesystem mount hierarchy.runccallspivot_rootto swap the namespace’s root/to the mounted image directory and unmount the old host root — a much stronger boundary than legacychroot.net(network stack): separate network interfaces, routing tables, TCP/UDP port spaces and packet-filtering rules. That is why two containers on the same laptop can both bind internal port8080without colliding.uts(UNIX Timesharing System): an independenthostnameand domain name.ipc(Inter-Process Communication): isolated POSIX/System V message queues and shared-memory segments (/dev/shm).cgroup: the process sees its own control-group subtree as/.user(optional — essential in rootless mode): mapsUID 0(root) inside the container to an ordinary unprivileged user ID on the host (for instanceUID 100000).
You can inspect that whole mechanism directly from the host with one command: ls -l /proc/<PID>/ns/ lists ordinary symlinks tagged with kernel inode IDs (pid:[...], net:[...], mnt:[...]). When you run docker exec -it name bash, you are not “logging into a VM” — the new process simply opens those files and invokes setns(2) to join the exact same namespaces.
A small detail with large consequences: PID 1 semantics
Because the container’s main process receives PID 1 inside its pid namespace, the kernel applies special Unix init rules to it:
- Default kernel handling for
SIGTERMandSIGINTis disabled forPID 1— if your program does not explicitly install a signal handler (for example, a simple script or a C binary withoutsigaction),docker stopsendsSIGTERM, nothing happens, and ten seconds later the daemon terminates it abruptly withSIGKILL. PID 1is responsible for reaping orphaned child processes (waitpid), otherwise zombie entries accumulate in the process table. That is whydocker run --initexists: it places a tiny reaper (such astini) atPID 1and launches your application asPID 2.
runc executes the ELF binary, it runs directly on the host kernel; the “container” is simply the set of kernel structures attached to that process.4. Pillar two: cgroups v2, CPU budgets and the multithreading trap
Namespaces control what a process can see, but they do not stop it from consuming all system RAM or saturating every CPU core on the machine. Accounting and enforcing physical resource limits belongs to a second kernel subsystem: cgroups v2 (Control Groups, version 2).
One of the most consequential misunderstandings in everyday work with Docker resource constraints is the difference between a CPU time quota (--cpus) and core pinning (--cpuset-cpus). When I ran a local test capping a container to half a core (--cpus 0.5), the cgroup v2 control files reported two seemingly contradictory facts:
- the quota file
cpu.maxread50000 100000, - yet the effective CPU mask (
cpuset.cpus.effective/ affinity mask) still exposed all0–11logical processors (all 12 hardware threads of the host).
Why does that matter? Writing 50000 100000 instructs the kernel scheduler (EEVDF on Linux 6.6+ and 7.0, the successor to CFS) to grant the entire control group a CPU quota inside every period . Average compute throughput is therefore of one core — yet the process still sees 12 logical cores and is allowed to run 12 threads simultaneously.
Look at what simple arithmetic predicts when a multithreaded program (a compiler, JVM, Go runtime, Python worker pool or inference engine) queries nproc, receives 12, and spins up busy worker threads (). CPU time is burned times faster than wall-clock time elapses. The entire quota runs dry after an active burst of only:
Plug in the numbers from my local test (, ):
- With thread: the program runs for , then the scheduler pauses it for until the next period starts.
- With threads: all 12 threads collectively consume the budget in just of wall-clock time, after which the entire container is frozen (throttled) for nearly !
Long-term average throughput still matches 0.5 cores, but tail latency is destroyed: any network request, measurement or camera frame arriving during the frozen stretch inherits an almost 100 ms stall out of nowhere — immediately visible in cpu.stat as climbing nr_throttled and throttled_usec counters (Section 7 presents real cpu.stat measurements for 1, 8 and 12 threads matching this formula to within fractions of a percent).
--cpus 0.5 (cpu.max = 50000 100000). The quota sums CPU time across every thread in the cgroup. The more threads an application spawns from nproc, the shorter its active burst and the longer the freeze inside each 100 ms window.It helps to separate two distinct operational goals here. When you want a fractional core (--cpus 0.5), the only effective way to rein in latency spikes is to cap the application’s own worker threads as well: in the Section 7 measurements, dropping from 12 threads to 1 cut the per-period pause from 95.83 ms to 50 ms and aggregate thread wait from 22.99 s to 1.00 s. When instead you can assign a whole number of cores (1, 2, 4…) and want to avoid periodic 100 ms quota freezes altogether, --cpuset-cpus (writing cpuset.cpus with no cpu.max quota) restricts the container to specific logical cores: threads still contend on that core’s ordinary runqueue, but the scheduler never freezes the cgroup for the remainder of a period. Memory limits in cgroups v2 (memory.max and memory.high) are equally worth understanding: a container’s memory accounting includes not only anonymous heap and stack allocations, but also the file page cache charged to that cgroup. That is why docker stats can report 90–95% memory usage with no leak at all — as long as most of it is clean page cache, the kernel reclaims those pages automatically under pressure before the OOM killer ever runs. If usage hits memory.max and cache cannot be reclaimed, the kernel triggers the OOM killer inside that cgroup — terminating the container process instead of hanging the entire host.
In practice — size worker threads to the quota, not to
nproc: When capping a container to a fractional core with--cpus(for background builds or throttled services), also cap the application’s own thread count explicitly (-j 1,OMP_NUM_THREADS,GOMAXPROCS). When you can dedicate full cores and want zero periodic quota stalls, pin them with--cpuset-cpus. Otherwise an application readingnprocdrives itself into recurring ~100 ms stalls.
5. Pillar three: OCI images, layer graphs and OverlayFS (Copy-on-Write)
The third pillar explains both why container images save disk space and why disk writes can suddenly stall. We need to keep two layers strictly separate: the immutable OCI image and the OverlayFS layered filesystem of a running container.
An OCI image as a content-addressed graph
Under the OCI Image Manifest Specification v1.1.1, a container image is not a single monolithic disk file (like .vdi or .qcow2), but a stack of immutable layers (compressed tar/gzip or zstd archives) bound together by a JSON manifest and a configuration file. Every layer and manifest is addressed by the SHA-256 hash of its bytes — its digest (such as sha256:28bd5f…). A tag like alpine:latest or python:3.12 is merely a mutable human-readable pointer to a digest at a given moment.
Content addressing immediately implies two practical mathematical properties.
First — disk deduplication. If your SSD holds images and each image consists of a set of layer blobs , summing the SIZE column in docker image ls counts shared base layers over and over. Actual storage consumed by the image blobs is the sum over the set union of unique layers:
Check that on an illustrative calculation: if 10 application images share of OS and library layers while each adds of application code, adding up docker image ls displays an alarming (). Actual disk usage is just — only of the apparent sum. To inspect the real split between shared (SHARED SIZE) and unique (UNIQUE SIZE) layers on your machine, run docker system df -v.
Second — update economics (delta blobs). Under the OCI Distribution Specification, pulling a newer image when is already cached transfers only the set difference:
Because every instruction in a Dockerfile stacks a new layer on top of the previous ones, modifying a file in a lower layer invalidates the digests of every layer above it. If you run COPY . . before installing of dependencies, changing one line of code forces rebuilding and transferring . Installing dependencies first and placing application code at the very top reduces the update to a sub-megabyte top blob.
OverlayFS and the hidden cost of Copy-on-Write (copy-up)
Starting a container does not copy hundreds of megabytes out of the image. Instead, the kernel mounts OverlayFS inside the container’s mnt namespace (Docker storage drivers documentation), merging two (or more) directory trees into a single merged view:
lowerdir(read-only): the unpacked stack of OCI image layers, shared across every container launched from that image.upperdir(writable): an initially empty private directory belonging solely to that container instance (alongside aworkdirrequired by the kernel for atomic operations).
Reading files from lowerdir runs at near-native host filesystem speed (once opened, pages sit in the kernel page cache and can even be shared in RAM across multiple containers of the same image). Behavior changes sharply on the first modification to any file originating in the image — even changing one byte, appending one line to a log, or running chmod (with metacopy disabled by default):
- Because
lowerdiris immutable, the kernel performs acopy-up: it copies the entire target file fromlowerdirintoupperdirfirst, and only then applies the write. Appending a single byte to a 200 MB image file triggers a physical 200 MB copy on the first write (116.9 msin my Section 7 benchmark); the second write hitsupperdirdirectly and completes in10.3 µs. - Deleting a
lowerdirfile does not free space in the image — OverlayFS creates a special whiteout marker (character device0/0) inupperdirthat merely hides the lower file frommerged. That is why deleting a large archive in a laterRUN rm ...layer of aDockerfilenever shrinks the resulting image. upperdirremains on disk after the container exits until you explicitly rundocker rm— which is whydocker cpcan still extract files from a crashed container, and whether it is running or stopped you can inspect every path added (A), changed (C, including viacopy-up), or hidden via whiteout (D) withdocker diff <name>.
By contrast, Docker volumes and bind mounts bypass OverlayFS altogether: reads and writes go straight to the host’s native filesystem (ext4, XFS, ZFS) with zero copy-up penalty and lifecycles independent of the container. Databases, large working files and camera capture directories should never write into upperdir.
lowerdir layers are shared and read-only; the first modification to an image file forces an expensive copy-up into upperdir. Volumes and bind mounts write straight to host storage.6. Networking, security boundaries and the cross-ISA emulation trap
The remaining component of our overhead equation () and the hard boundaries of containerization show up in virtual networking, syscall security and mixing CPU architectures.
Networking: why default bridge costs more than --network host
By default, Docker assigns each container its own net namespace connected to the outside world through a virtual Ethernet (veth) pair: one end lives inside the container as eth0, while the other plugs into a software bridge (docker0 or a Compose project bridge) on the host. Outbound traffic and published ports (-p 8080:8080) traverse that bridge, Linux connection tracking (conntrack) and NAT translation (iptables / nftables).
In IBM Research’s classic comparison of virtual machines and containers (Felter et al., An Updated Performance Comparison of Virtual Machines and Linux Containers, Table I), this split stood out sharply: while CPU and memory performance inside containers practically matched native execution, virtual NAT networking and layered filesystems introduced measurable overhead under high rates of small packets and I/O requests. Switching to --network host (sharing the host’s network namespace) removes those extra hops at the cost of port isolation, whereas --network none leaves only loopback lo (127.0.0.1) — giving a hard guarantee of offline isolation.
Security without illusions: capabilities, seccomp and the shared kernel
A common architectural mistake is treating a container as a sandbox safe enough for arbitrary untrusted code downloaded from the internet. Assessing real isolation requires knowing what actually guards the process:
- Linux Capabilities: traditional all-powerful root privileges are split into dozens of discrete capabilities (
CAP_SYS_ADMIN,CAP_NET_ADMIN,CAP_SYS_TIME, etc.). Docker’s default profile drops most of them, so evenUID 0inside a container cannot mount disks or load kernel modules (unless you disable those safeguards with--privileged). seccomp-bpf: a BPF filter attached to the process that blocks dozens of risky or unnecessary syscalls (such askexec_load,reboot,mount), shrinking the kernel attack surface.--read-onlyand rootless mode: mounting the root filesystem read-only (with explicittmpfsmounts for temporary directories) and mapping containerUID 0to an unprivileged host UID contain the blast radius if an application is compromised.
Even with all three enabled, the fundamental boundary remains unchanged: every container on the machine issues syscalls against the same Linux kernel. A kernel bug reachable through an allowed syscall (in the network stack, io_uring or filesystem code) can potentially break isolation across the entire host. Containers are excellent for isolating dependencies, configuration and bugs in ordinary software; when you must run hostile, untrusted code (as in multi-tenant clouds), the security boundary needs to drop one layer lower — to hardware virtualization (microVMs such as Firecracker or Kata) or user-space syscall interception (gVisor).
When a container stops being native: multi-platform images and QEMU (binfmt_misc)
In my article on CPU architectures and binary translation, I explained why x86-64 machine code cannot execute natively on Arm64 cores (and vice versa). OCI solves distribution with an OCI Image Index — a top-level manifest referencing separate native images for linux/amd64, linux/arm64 and other targets so each host pulls its own native binaries.
Docker can also run an arm64 image on an x86-64 PC by pairing the Linux binfmt_misc handler with user-mode QEMU. Remember one rule whenever that happens: all the “near-zero overhead” from Section 1 vanishes. Every ARM instruction passes through software binary translation onto x86-64 (Docker explicitly warns about QEMU emulation cost). It is convenient for quick sanity checks or simple packaging, but completely unsuitable for judging real performance on target ARM hardware.
7. Overhead balance sheet: four local measurements and one networking caveat
To keep the remaining terms of grounded in real numbers rather than theory, I ran three additional micro-benchmarks on the exact same machine (AMD Ryzen 5 7600 6-Core / 12 threads, Linux 7.0.0-44-generic, GCC 15.2.0, Docker Engine 29.1.3, CgroupDriver=systemd, cgroups v2, StorageDriver=overlayfs), using small statically linked C binaries timed with CLOCK_MONOTONIC.
| Overhead component | Container-side kernel mechanism | Local measurement (or literature) | Practical impact |
|---|---|---|---|
| (loop) | Same ELF in ring 3, pinned core (CPU 4) | Measured (7 pairs): Host med. 196.4 ms (184.8–213.8), Container med. 189.0 ms (184.5–213.5) — no detectable overhead | Long CPU computations run at native silicon speed inside Linux containers |
dockerd API + containerd + runc + OverlayFS | Measured (11 pairs, nic.c): Host ./nic med. 0.37 ms (0.33–0.41 ms) vs. docker run med. 296.7 ms (284.6–302.3 ms) — fixed ~296 ms/start overhead | Negligible for long jobs (+3% on 10 s), rules out spawning tiny CLIs in a tight loop | |
OverlayFS copy-up (lowerdir upperdir) | Measured (7 runs, 200 MB file, warm cache): OverlayFS 1st write med. 116.9 ms (111.7–120.9), 2nd write med. 10.3 µs; bind mount 1st write 14.3 µs | One-time cost proportional to full file size; keep databases and scratch on volumes | |
cgroups v2 throttling | cpu.max = 50000 100000 with visible CPUs 0–11 | Measured (5 runs × 2 s, cpu.stat): --cpus 0.5: 1 thr 1.00 s (20/21 per.), 8 thr 15.05 s (~1.88 s/thr), 12 thr 22.99 s (sum across 12 thr, ~1.92 s/thr); --cpuset-cpus=4 (1 full core, no cpu.max): 0 s | Tail-latency trap for apps that size thread pools from nproc (100 ms stalls) |
| (NAT) | veth pair + bridge + conntrack/NAT | Documented in literature: IBM Research (Felter et al., Table I) — no local packet test | Matters at high small-packet rates; --network host removes the extra hops |
What the three micro-benchmarks showed in detail
-
Fixed container startup cost (): I compiled an empty static no-op binary
nic.c(Polish for “nothing”:int main(void){return 0;}with-O2 -static) and timed wall-clock execution from an external C wrapper (fork+execvp+waitpidwithCLOCK_MONOTONIC, 1 warm-up + 11 alternating pairs) comparing./nicagainstdocker run --rm --pull=never --read-only --network none --mount "type=bind,src=$PWD/nic,dst=/nic,readonly" alpine /nic. The native process finished in a median of0.37 ms(0.332–0.407 ms), whereas a fulldocker run --rmcycle took a median of296.7 ms(284.552–302.331 ms). That is a fixed ~300 mssetup-and-teardown overhead acrossdockerd,containerdandrunc. Because it does not scale with runtime, it adds only ~3% to a 10-second compilation and disappears in a 10-minute build; invoked in a tight loop dozens of times per second, however, it dominates throughput. -
One-time OverlayFS
copy-upcost: I built a localalpine-based image containing a single non-sparse, incompressible 200 MB file (/data.binfrom/dev/urandom) and measured onlyopen(O_WRONLY|O_APPEND)+ a 1-bytewrite+closeinside the container (warm page cache, nofsyncand no manual cache drop, 1 warm-up + 7 fresh containers). The first write to the image file — forcing Linux to copy all 200 MB fromlowerdirintoupperdir— took a median of116.9 ms(111.7–120.9 ms). The second write to the same file (already inupperdir) dropped to10.3 µs(9.2–14.8 µs), and on an identical 200 MB file passed through a bind mount even the first write completed in a median of14.3 µs(12.5–20.7 µs; second write:4.7 µs). Turning those two numbers into a dramatic multiplier would be misleading: for a 4 KB file the ratio would be modest, and for a 2 GB file far larger. The physical property of OverlayFS is that the first modification pays a one-time cost proportional to the full file size (here ~117 msfor 200 MB), after which subsequent writes inupperdir— as well as writes on bind mounts or volumes — take single-digit microseconds. -
cgroups v2throttling counters (cpu.stat): I ran a static multithreaded C program burning CPU for exactly 2 seconds of wall-clock time (CLOCK_MONOTONIC, 5 trials per configuration) and read/sys/fs/cgroup/cpu.stat:- with
--cpus 0.5and 1 thread:nr_periods = 21,nr_throttled = 20(range20–21), medianthrottled_usec = 999,849 µs(1.00 s),usage_usec ≈ 1.05 s; - with
--cpus 0.5and 8 threads:nr_throttled = 21(100% of active periods), medianthrottled_usec = 15,054,234 µs(15.05 s— sum across 8 threads, ~1.88 swait per thread),usage_usec ≈ 1.06 s; - with
--cpus 0.5and 12 threads:nr_throttled = 21(100% of active periods), medianthrottled_usec = 22,986,583 µs(22.99 s— sum across 12 threads, ~1.92 swait per thread),usage_usec ≈ 1.07 s; - as a control, with
--cpuset-cpus=4(a different type of constraint: 1 full core with nocpu.max, i.e., twice the CPU budget of--cpus 0.5, checked for both 1 and 12 threads):nr_periods = 0,nr_throttled = 0,throttled_usec = 0across all 10 trials (usage_usec ≈ 2.02 s). With 12 threads pinned to one core, the threads still contend on that core’s runqueue, but they do not incur periodic 100 ms quota freezes.
An important accounting detail explains why
throttled_useccan exceed 2 seconds and reach22.99 sinside a 2-second test: incgroups v2, this counter sums throttled duration across all active per-CPU runqueues holding runnable threads (which on a 12-thread processor scales proportionally to for ). Across the 20 full 100 ms periods fitting inside a 2-second window (spanning 21 period boundaries incpu.stat), the analytical expectation is therefore : for that predicts (measured1.00 s), for it predicts (measured15.05 s), and for it predicts (measured22.99 s). The live EEVDF scheduler confirmed the equation from Section 4 to within a fraction of a percent. - with
copy-up and multithreaded cgroups v2 throttling.In practice — before blaming Docker for a slowdown: Decompose the workload with . If a process performs heavy CPU or GPU work inside a long-lived job, native Linux container overhead is virtually zero. If you see 100 ms stutters, check
cpu.stat(nr_throttled); if writes crawl, check whether you are hittingupperdiror the Docker Desktop file bridge; and if you pulled a foreign-ISA image, verify that silent QEMU emulation is not running underneath.
8. What follows from these mechanics in practice?
Once you see a container as an ordinary process wrapped in four lightweight kernel structures and a SHA-256 content-addressed filesystem, it stops looking like “heavy cloud-server machinery.” Very down-to-earth workflows fall directly out of the same primitives:
mntnamespace isolation and:romounts let you expose a family photo archive or local AI model weights without risking accidental modification or deletion.netnamespaces and embedded DNS let you run two conflicting versions of the same service side by side on one laptop, or prove that a tool truly works offline (--network none).- Immutable OCI digests and layer deduplication let you rebuild firmware for a three-year-old board, catch regressions in an identical environment and ship a complete product onto an air-gapped shop floor.
In the companion practical guide — Docker and Containers in Practice: From One-Off Tools and Local LLMs to Shared Memory and Offline Deployments — I move entirely to concrete use cases, fast host–container IPC (mmap, Unix sockets), workshop patterns and the situations where containers add unnecessary friction compared to native execution.
9. Sources and further reading
Linux kernel: namespaces, cgroups v2, OverlayFS and security
- Linux man-pages —
namespaces(7)andsetns(2)— overview of Linux namespaces (mnt,pid,net,ipc,uts,user,cgroup,time) and howdocker execjoins a running container. - Linux kernel documentation — Control Group v2 (
cgroup-v2) — specification ofcpu.max,cpu.stat,cpusetandmemory.maxaccounting. - Linux kernel documentation — Overlay Filesystem (
overlayfs) —lowerdir,upperdir, whiteout entries andcopy-upmechanics. - Linux man-pages —
capabilities(7)and kernel docs — Seccomp BPF — split root privileges and syscall filtering.
OCI standards, Docker and runtime architecture
- OCI Image Specification v1.1.1 — Manifest and OCI Distribution Specification v1.1.1 — manifests, digests and layer blob distribution.
- OCI Runtime Specification — contract between daemons like
containerdand low-level runtimes such asrunc. - Docker Docs — Resource constraints, Storage drivers,
docker container diffanddocker system df— how kernel knobs map to Docker flags, liveupperdirinspection, andSHARED SIZE/UNIQUE SIZEaccounting. - Docker Docs — Network driver
none, Virtual Machine Manager in Docker Desktop and Multi-platform builds (QEMU emulation cost).
Performance studies
- Wes Felter, Alexandre Ferreira, Ram Rajamony, Juan Rubio (IBM Research) — An Updated Performance Comparison of Virtual Machines and Linux Containers (Table I) — classic benchmark comparing CPU, memory, disk and NAT network performance across native Linux, containers and virtual machines.