Skip to main content

Linux Containers: Namespaces & cgroups

Learning objectives
  • Explain a container as "a process with namespaces, cgroups, a root filesystem and security filters" and build one by hand
  • Describe each namespace type and what it isolates, including how pods share namespaces
  • Use cgroup v2 controllers (cpu, memory, io, pids) and map Kubernetes requests/limits/QoS onto them
  • Explain overlayfs image layers, copy-up and why secrets in a lower layer never really disappear
  • Harden a Go service container (capabilities, seccomp, non-root, read-only root, user namespaces) for a regulated environment

TL;DR​

  • A container is not a VM. It is an ordinary Linux process tree with namespaces (what it can see), cgroups (what it can use), a root filesystem from image layers, and security filters (capabilities, seccomp, LSMs). All containers share the host kernel.
  • Namespaces: mnt, pid, net, uts, ipc, user, cgroup (and time). Containers in a Kubernetes pod share the network and IPC namespaces through the pod sandbox.
  • cgroups v2 is one unified hierarchy under /sys/fs/cgroup; key files are cpu.max, cpu.weight, memory.max, memory.high, io.max, pids.max, plus PSI pressure files.
  • Kubernetes: CPU request → cpu.weight, CPU limit → cpu.max, memory limit → memory.max; QoS class decides oom_score_adj and eviction order.
  • Images are stacks of read-only, content-addressed layers combined by overlayfs; writes go to a per-container upper layer via copy-up. Deleting a file in a later layer only hides it.
  • Runtimes: kubelet → CRI → containerd → shim → runc (which sets up namespaces/cgroups and execs your binary, then exits).
  • Security: drop all capabilities, use the RuntimeDefault seccomp profile, run as non-root with a read-only root filesystem, and use user namespaces or sandboxed runtimes (gVisor, Kata) for untrusted code. A kernel exploit escapes any plain container.

Why it matters​

Almost every Go service you design will run in a container on Kubernetes. Many of the production mysteries on other pages — CPU throttling, OOMKilled with a small heap, PID 1 not handling SIGTERM, nproc reporting 64 cores in a 2-CPU pod — come from namespaces and cgroups. Understanding them turns "Kubernetes is weird" into predictable behaviour you can design for.

In banking, containers also raise compliance and isolation questions. A PCI DSS assessor will ask how the cardholder-data environment is segmented from other workloads on shared nodes; a security review will ask whether a compromised container can reach the host. "It's in a container" is not an answer — the answer is the specific namespaces, capabilities, seccomp profile, user mapping, network policy and node isolation you configured.

Core concepts​

What a container is​

There is no "container" object in the kernel. runc calls clone()/unshare() with namespace flags, writes cgroup files, mounts the root filesystem, applies capability and seccomp filters, then execs your entrypoint. From the host, ps shows your process like any other.

Namespaces​

NamespaceIsolatesWhat it means for your service
mntMount tableContainer sees its own root filesystem and mounts (volumes, /proc)
pidProcess IDsYour binary is PID 1 inside; must handle signals and reap children (see Processes & Threads)
netInterfaces, routes, iptables, ports, socketsOwn eth0 (a veth pair to the host), own loopback; port 8080 in two pods doesn't clash
utsHostname, domain nameos.Hostname() returns the pod name
ipcSystem V IPC, POSIX message queuesShared memory segments are private to the pod
userUID/GID mappings, capabilities scopeRoot inside can map to an unprivileged UID outside (rootless containers)
cgroupView of the cgroup hierarchy/sys/fs/cgroup inside shows only the container's own subtree
timeMonotonic/boot clocks offsetsRarely used; for checkpoint/restore

Tools: lsns lists namespaces; ls -l /proc/PID/ns shows a process's namespace IDs; nsenter -t PID -n ip addr runs a command inside a container's network namespace (invaluable for debugging distroless containers that have no shell); unshare creates new namespaces from the shell.

Pods share namespaces. Kubernetes first starts a tiny sandbox ("pause") container that holds the pod's network and IPC namespaces; app containers and sidecars join them. That is why a sidecar proxy can intercept localhost traffic and containers in a pod talk over 127.0.0.1. PID namespace sharing is optional (shareProcessNamespace: true).

cgroups v2​

cgroups (control groups) organise processes into a tree and apply resource controllers to each node. cgroup v2 (default on modern distros; Kubernetes support GA in 1.25) uses a single unified hierarchy mounted at /sys/fs/cgroup.

ControllerKey filesEffect
cpucpu.weight (1–10000, default 100), cpu.max ("quota period"), cpu.stat, cpu.pressureProportional share under contention; hard cap per period (throttling)
memorymemory.max, memory.high, memory.low/min, memory.current, memory.stat, memory.eventsHard limit with OOM kill; soft throttle; reclaim protection; accounting incl. page cache and kernel memory
ioio.max (per-device rbps/wbps/riops/wiops), io.weight, io.stat, io.pressureBandwidth/IOPS caps and proportional I/O share; v2 can attribute buffered write-back to the right cgroup
pidspids.max, pids.currentCaps processes+threads — fork-bomb and thread-leak protection
cpusetcpuset.cpus, cpuset.memsPin to CPUs and NUMA nodes (CPU Manager static policy)
hugetlbhugetlb.2MB.maxHuge page reservations

cgroup v2 improvements over v1 that matter to you: one consistent tree (no mismatched per-controller hierarchies), memory.high soft limits, PSI pressure files per cgroup, and correct write-back accounting so io.max can throttle buffered writes. Details of the CPU and memory controllers are in CPU Scheduling and Memory Management.

# From inside a container (cgroup namespace shows only your subtree)
cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/memory.max /sys/fs/cgroup/pids.max
cat /sys/fs/cgroup/memory.events /sys/fs/cgroup/cpu.stat
# From the node: the pod's cgroup path (systemd driver, cgroup v2; layout approximate)
systemd-cgls --no-pager | grep -A3 kubepods

Kubernetes resources → cgroups​

Pod specLinux mechanismBehaviour
requests.cpu: 500mcpu.weight (from v1-style shares 512; ≈ 20 with the classic conversion, exact value depends on runtime version)Proportional share only when the node is busy; scheduler uses it for placement
limits.cpu: "2"cpu.max = 200000 100000Throttled after 200 ms of CPU per 100 ms period
requests.memory: 512MiScheduler placement; eviction ranking (memory QoS features may also set memory.min)Not enforced at runtime by default
limits.memory: 1Gimemory.max = 1073741824Reclaim, then OOM kill inside the container — exit 137, OOMKilled
QoS: Guaranteed (requests = limits for all containers)oom_score_adj = -997, kubepods sliceLast to be evicted or OOM-killed
QoS: Burstableoom_score_adj between 2 and 999 by request sizeMiddle
QoS: BestEffort (no requests/limits)oom_score_adj = 1000First to go under node pressure
Kubelet podPidsLimitpids.maxfork/thread creation fails beyond it

Node-level protections sit above this: kube-reserved/system-reserved keep CPU and memory for the kubelet and system daemons, and kubelet eviction (default hard threshold memory.available<100Mi on Linux) evicts pods before the kernel OOM killer has to act.

Overlay filesystems and image layers​

An OCI image is a manifest listing a config and an ordered set of layers (tarballs), each identified by its sha256 digest. Identical layers are stored and pulled once and shared by every image that uses them.

  • overlayfs stacks read-only lowerdirs with one writable upperdir; a workdir supports atomic operations. Lookups go top-down.
  • Copy-up: modifying a file from a lower layer copies the whole file to the upper layer first — slow for large files, and wasteful. Databases and queues must use volumes, never the container filesystem.
  • Whiteouts: deleting a lower-layer file creates a whiteout marker in the upper layer. The bytes remain in the lower layer. A secret COPYed in one Dockerfile step and rmed in the next is still in the image — extract it with docker save and tar. Use build secrets (RUN --mount=type=secret) or multi-stage builds.
  • Layer caching: each Dockerfile instruction is a layer; order from least to most frequently changing (go.mod/go.sum and go mod download before COPY . .).
  • containerd's snapshotter (overlayfs by default) prepares these mounts; /var/lib/containerd holds layers on the node, so image bloat costs disk on every node and slows cold starts during scale-out.

Container runtimes​

  • OCI runtime spec: a bundle = config.json (namespaces, cgroups, mounts, capabilities, seccomp) + root filesystem. runc is the reference implementation; crun (C) and youki (Rust) are alternatives.
  • High-level runtimes: containerd (used by Docker Engine and most Kubernetes distros) and CRI-O pull images, manage snapshots and supervise containers. Kubernetes removed its built-in Docker integration (dockershim) in 1.24; Docker-built images still run unchanged because they are OCI images.
  • The shim lets runc exit after starting the container and lets containerd restart without killing containers.
  • Sandboxed runtimes add a second isolation boundary: gVisor intercepts syscalls with a user-space kernel; Kata Containers and Firecracker run each pod in a lightweight VM (AWS Lambda runs on Firecracker microVMs). Select per workload with a Kubernetes RuntimeClass.

Security: what stands between a container and the host​

LayerMechanismRecommended setting
IdentityNon-root UID; user namespacesrunAsNonRoot: true, runAsUser: 10001; hostUsers: false where supported
PrivilegesLinux capabilities (root's power split into ~40 units)drop: ["ALL"]; add back only what you need (rarely NET_BIND_SERVICE)
Privilege escalationno_new_privs (blocks setuid binaries gaining privileges)allowPrivilegeEscalation: false
Syscallsseccomp BPF filterseccompProfile: RuntimeDefault (blocks dozens of rarely needed, risky syscalls such as kexec_load, reboot, module loading)
MACAppArmor / SELinuxRuntime default profiles; custom for sensitive workloads
FilesystemRead-only root, no host mountsreadOnlyRootFilesystem: true; emptyDir for /tmp
Neverprivileged: true, hostPID, hostNetwork, mounting /var/run/docker.sock or the containerd socketEach one is effectively root on the node

Notes:

  • Docker's default capability set keeps about 14 capabilities (e.g. CHOWN, NET_RAW, SETUID, KILL); most Go services need none of them. CAP_SYS_ADMIN is so broad it is nicknamed "the new root".
  • Rootless containers (Podman rootless, Docker rootless mode, Kubernetes user namespaces) map container UID 0 to an unprivileged host UID range from /etc/subuid, so escaping the container as "root" yields an ordinary user.
  • Real escapes happen. runc CVE-2019-5736 let a malicious container overwrite the host's runc binary; CVE-2024-21626 ("Leaky Vessels") was an internal file-descriptor leak that let a container process start with its working directory on the host filesystem. Kernel bugs such as Dirty Pipe (CVE-2022-0847) work from inside containers because the kernel is shared. Patch runtimes and kernels, and isolate untrusted or high-value workloads on separate nodes or sandboxed runtimes.
  • Kubernetes Pod Security Standards (privileged, baseline, restricted), enforced by Pod Security Admission, codify most of the table above. See Security for Architects.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Plain containers (runc)Fast start (≈ tens to hundreds of ms), dense packing, native performanceShared kernel: one kernel exploit away from the hostYour own trusted services on hardened nodes
Rootless / user-namespaced containersEscape lands as an unprivileged userSome features (certain mounts, low ports, some volume types) need workaroundsMulti-team clusters, CI runners, defence in depth
gVisorSyscall-level isolation without VMsSyscall overhead (I/O-heavy apps slower); compatibility gapsRunning untrusted code (plugins, user scripts)
Kata / Firecracker microVMsVM-grade isolation with container UXHigher start latency and memory overhead; nested virtualisation constraintsMulti-tenant platforms, regulated workloads needing strong isolation
Full VMs per serviceStrongest isolation, familiar to auditorsSlow provisioning, poor density, more opsLegacy core banking, appliances, strict segmentation mandates

In practice​

A minimal, hardened image for a Go service:

# Dockerfile
FROM golang:1.25 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/payments ./cmd/payments

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/payments /payments
USER nonroot:nonroot
ENTRYPOINT ["/payments"]
  • CGO_ENABLED=0 gives a static binary that runs on distroless/static or scratch. With scratch, you must add CA certificates yourself, and for time zones either copy zoneinfo or import time/tzdata (Go 1.15+), which embeds the database in the binary.
  • Exec-form ENTRYPOINT makes your binary PID 1 so it receives SIGTERM directly.

The matching pod spec fragment:

apiVersion: v1
kind: Pod
metadata:
name: payments
spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: payments
image: registry.example.com/payments@sha256:4f3c...
resources:
requests:
cpu: "1"
memory: 768Mi
limits:
memory: 1Gi
env:
- name: GOMEMLIMIT
value: "900MiB"
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir:
sizeLimit: 64Mi

Pin images by digest in regulated environments so the artefact that passed the security scan is exactly what runs.

Building a "container" by hand demystifies it (run in a disposable Linux VM as root):

# Root filesystem from an image
mkdir -p /tmp/ctr/rootfs && cd /tmp/ctr
docker export "$(docker create alpine:3.20)" | tar -C rootfs -xf -

# cgroup with limits
mkdir /sys/fs/cgroup/demo
echo "50000 100000" > /sys/fs/cgroup/demo/cpu.max # 0.5 CPU
echo $((128*1024*1024)) > /sys/fs/cgroup/demo/memory.max
echo 64 > /sys/fs/cgroup/demo/pids.max
echo $$ > /sys/fs/cgroup/demo/cgroup.procs # move this shell in

# New namespaces + chroot; ps inside shows PID 1
unshare --pid --fork --mount --uts --ipc --net --mount-proc=rootfs/proc \
chroot rootfs /bin/sh -c 'hostname demo; ps; ip link; exec sh'

The same in Go (the core of Liz Rice's "Containers From Scratch" talk), using SysProcAttr:

//go:build linux

package main

import (
"fmt"
"os"
"os/exec"
"syscall"
)

func main() {
if len(os.Args) < 3 {
fmt.Println("usage: mini run|child CMD [ARGS...]")
os.Exit(2)
}
switch os.Args[1] {
case "run":
run()
case "child":
child()
}
}

// run re-executes this binary as "child" inside new namespaces.
func 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,
Unshareflags: syscall.CLONE_NEWNS, // keep mounts out of the host namespace
}
must(cmd.Run())
}

func child() {
fmt.Printf("running %v as PID %d\n", os.Args[2:], os.Getpid()) // prints PID 1
must(syscall.Sethostname([]byte("container")))
must(syscall.Chroot("/tmp/ctr/rootfs"))
must(os.Chdir("/"))
must(syscall.Mount("proc", "proc", "proc", 0, ""))
defer syscall.Unmount("proc", 0)

cmd := exec.Command(os.Args[2], os.Args[3:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
must(cmd.Run())
}

func must(err error) {
if err != nil {
panic(err)
}
}

Common pitfalls​

  • Assuming container = security boundary. Running untrusted code (customer-supplied scripts, report templates) in plain containers next to payment services. One kernel exploit compromises the node.
  • Privileged or socket-mounted containers for CI or monitoring agents. Symptom in an audit: any compromise of that pod is root on the node.
  • Secrets baked into layers. COPY .env then RUN rm .env. The file is still in the image history and registry.
  • Writing heavy data to the container filesystem. Copy-up and overlay overhead, data lost on restart, node disk filling up. Symptom: kubelet evicts pods for ephemeral-storage pressure.
  • Sizing from /proc inside the container. nproc, /proc/meminfo and /proc/loadavg show host values (unless something like LXCFS is used); read cgroup files instead.
  • No pids.max / pod PID limit. A thread leak or fork loop exhausts the node's PIDs and breaks unrelated pods. Symptom: fork: Resource temporarily unavailable across the node.
  • Huge images. 1–2 GiB images with build toolchains slow scale-out during a sale and increase CVE surface. Use multi-stage builds and distroless.
  • BestEffort pods in production. No requests means no protection: first to be evicted or OOM-killed, and the scheduler packs them blindly.

Interview angle​

  • "What is a container?" — the strong answer: a process with namespaces, cgroups, an overlay root filesystem and security filters, sharing the host kernel; contrast with a VM's own kernel and hardware virtualisation.
  • "How does a Kubernetes memory limit work?" — memory.max, what is charged (anon, page cache, kernel), reclaim then OOM kill, exit 137, QoS and oom_score_adj; and the Go angle: GOMEMLIMIT.
  • "How would you isolate PCI workloads on Kubernetes?" — dedicated node pools or clusters for the CDE, network policies, restricted Pod Security, non-root, dropped capabilities, seccomp, image signing and digest pinning, sandboxed runtimes for untrusted code, audit logging.
  • Follow-ups: how pods share namespaces; why secrets deleted in a later layer leak; what runc does vs containerd; cgroup v1 vs v2; why nproc lies.
  • Red flags: "containers are lightweight VMs"; "running as root inside a container is fine because it's isolated"; not knowing where limits are enforced.

Self-check​

1. List the namespaces a typical container gets and give one practical consequence of each.

mnt — own root filesystem and mounts; pid — your app is PID 1 and must handle signals and reaping; net — own interfaces and ports, so two pods can both bind 8080; uts — own hostname (pod name); ipc — private shared memory; user — UID mapping for rootless containers; cgroup — sees only its own cgroup subtree. Pod containers share the net and IPC namespaces via the sandbox container.

2. A pod has requests.cpu: 250m and limits.cpu: 1. What exactly does the kernel enforce?

cpu.weight derived from 250m sets its proportional share when CPUs are contended (it can use more when the node is idle). cpu.max = 100000 100000 caps it at 100 ms of CPU time per 100 ms period summed across all threads; beyond that it is throttled until the next period.

3. A developer copies a private key into an image, uses it in a RUN step, and deletes it in the next step. Is the key exposed? Why?

Yes. Each instruction creates a layer; the key exists in the layer that copied it, and the later deletion only adds a whiteout in a higher layer. Anyone who can pull the image can extract the earlier layer. Use build secrets mounts or a multi-stage build where the key never enters the final image's layers, and rotate the exposed key.

4. What happens step by step when the kubelet starts a container?

The kubelet asks containerd (via CRI) to create the pod sandbox and container. containerd pulls the image if needed, prepares an overlayfs snapshot, writes an OCI bundle (config.json + rootfs) and starts a shim. The shim invokes runc, which creates namespaces, configures cgroups, mounts filesystems, drops capabilities, applies seccomp and execs the entrypoint; runc exits and the shim supervises the process.

5. Why can't you trust /proc/meminfo or nproc inside a container, and what should a Go service read instead?

Those files and commands reflect the host (the namespaces don't virtualise them by default), so a 1 GiB, 2-CPU pod may see 256 GiB and 64 CPUs. Read /sys/fs/cgroup/memory.max and cpu.max (Go 1.25+ already uses the CPU limit for GOMAXPROCS; set GOMEMLIMIT from the memory limit).

6. Scenario: a bank wants to let merchants upload custom fraud-rule scripts that run in the platform. How do you isolate them?

Treat them as untrusted code: run them in a sandboxed runtime (gVisor or a microVM via Kata/Firecracker) selected by RuntimeClass, on a dedicated node pool away from payment services, as non-root with all capabilities dropped and a strict seccomp profile, read-only filesystem, no service-account token, egress denied by network policy, and tight cgroup limits (CPU, memory, pids, time limits). Also validate inputs, log and audit executions.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Build a container by hand, then compare it with what Kubernetes does.

  1. In a Linux VM, follow the shell recipe above: create a rootfs, a cgroup with cpu.max, memory.max and pids.max, and start a shell in new namespaces. Inside, verify ps shows PID 1, the hostname is isolated, and ip link shows only lo.
  2. Inside that cgroup, run a Go program that allocates memory until killed. Read memory.events and dmesg to confirm the cgroup OOM kill. Run a CPU burner and read cpu.stat for throttling.
  3. Build and run the Go mini container program; explain each Cloneflags value.
  4. Mount an overlay by hand (mount -t overlay overlay -o lowerdir=lower,upperdir=upper,workdir=work merged), modify and delete files in merged, and inspect upper to see the copied-up file and the whiteout.
  5. On a Kubernetes node (kind or minikube is fine), deploy the hardened pod above and locate its cgroup directory; read cpu.weight, cpu.max and memory.max and confirm they match the spec. Check /proc/PID/status for CapEff and Seccomp.

Done looks like: a short lab note with the commands you ran, the observed cgroup values next to the pod spec, the OOM and throttling evidence, and the overlay directory listings.

Further reading​

Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).