Skip to main content
Foundations: web, servers, containersLesson 9 of 13

How Linux Isolates a Container

A container is not a small virtual machine. It is an ordinary process on the host that the kernel shows a smaller world (namespaces) and holds to a budget (cgroups). Follow one container from start to an OOM kill.

PID (inside / host)1 / 4321
CPU—
Memory—
Exit—
Linux host · one shared kernelContainer runtimecontainerd · runcLinux kernelShared by allProcessHost PID 4321NamespacesWhat it can seecgroupWhat it can useOwn networketh0 · own IPOwn filesystemImage layersOOM killerSIGKILLclone · unshareNew process
RequestWatchAppears in a later step

What you will learn

  • A container is a normal process that ps on the host can see
  • Each namespace hides one kind of resource: PIDs, network, mounts, hostname, IPC, users
  • Why PID 1 inside a container is special
  • cgroup v2 files: cpu.max throttles, memory.max kills
  • Why an OOM-killed container exits with code 137

Namespaces and cgroup files at a glance​

WhatIsolates or limitsWhere to look
pid namespaceProcess IDs; the entrypoint is PID 1 insidels -l /proc/<pid>/ns/pid
net namespaceInterfaces, IP addresses, routes, portsip netns, nsenter -t <pid> -n ip addr
mnt namespaceMount table; the image is mounted as /cat /proc/<pid>/mountinfo
uts namespaceHostnamensenter -t <pid> -u hostname
ipc namespaceSystem V IPC and POSIX message queueslsns -t ipc
user namespaceUID/GID mapping (root inside, unprivileged outside)cat /proc/<pid>/uid_map
cpu.maxCPU limit as quota and period; over it the process is throttledcat cpu.max, cat cpu.stat
cpu.weightShare of CPU under contention (from requests)cat cpu.weight
memory.maxHard memory limit; over it the OOM killer runscat memory.max, cat memory.events

Try it yourself​

sudo unshare --pid --fork --mount-proc --uts bash # A shell in new pid and uts namespaces
ps -ef; hostname demo; hostname # Inside: bash is PID 1, hostname change stays inside
lsns # On the host: list namespaces and their first process
PID=$(pgrep -f <container-cmd> | head -1) # Host PID of a container process
ls -l /proc/$PID/ns # Its namespace IDs
cat /proc/$PID/cgroup # Its cgroup path under /sys/fs/cgroup
cat /sys/fs/cgroup/<that path>/{cpu.max,memory.max,cpu.stat,memory.events} # Limits, throttling, oom_kill
kubectl get pod <pod> -o jsonpath='{.status.containerStatuses[*].lastState.terminated.exitCode}' # 137 after an OOM kill

Check yourself

  1. A container has a 0.5 CPU limit. Under load its latency jumps, but it never restarts. What is happening?
  2. A container exits with code 137 and Kubernetes shows OOMKilled. What does 137 mean?
  3. An app runs as PID 1 in its container and has no SIGTERM handler. What happens when Kubernetes stops the Pod?

Further reading: namespaces(7) · pid_namespaces(7) · user_namespaces(7) · Control Group v2 · About cgroup v2 (Kubernetes) · User Namespaces (Kubernetes) · From One Server to Containers · Requests and Limits