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—
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
| What | Isolates or limits | Where to look |
|---|---|---|
| pid namespace | Process IDs; the entrypoint is PID 1 inside | ls -l /proc/<pid>/ns/pid |
| net namespace | Interfaces, IP addresses, routes, ports | ip netns, nsenter -t <pid> -n ip addr |
| mnt namespace | Mount table; the image is mounted as / | cat /proc/<pid>/mountinfo |
| uts namespace | Hostname | nsenter -t <pid> -u hostname |
| ipc namespace | System V IPC and POSIX message queues | lsns -t ipc |
| user namespace | UID/GID mapping (root inside, unprivileged outside) | cat /proc/<pid>/uid_map |
cpu.max | CPU limit as quota and period; over it the process is throttled | cat cpu.max, cat cpu.stat |
cpu.weight | Share of CPU under contention (from requests) | cat cpu.weight |
memory.max | Hard memory limit; over it the OOM killer runs | cat 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
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