cgroups and namespaces in Linux: the basis of containers

Updated November 1, 2026

cgroups and namespaces are two kernel mechanisms behind containers: cgroups limit resources, namespaces isolate processes.

Common cases

systemd-cgls               # the cgroup tree with processes
systemctl status nginx     # a service's cgroup shows at the bottom
cat /sys/fs/cgroup/...     # cgroup limits and counters
lsns                       # list the namespaces on the system
ls -l /proc/$$/ns          # which namespaces the shell is in

Sample output

$ cat /sys/fs/cgroup/memory.max
268435456
$ cat /sys/fs/cgroup/cpu.max
50000 100000
$ free -h
               total        used        free      shared  buff/cache   available
Mem:            11Gi       1.2Gi       9.7Gi       164Mi       1.2Gi        10Gi
Swap:           12Gi          0B        12Gi
$ lsns -t pid
        NS TYPE NPROCS PID USER    COMMAND
4026533389 pid       1   1 student lsns -t pid

How it works: limits plus isolation

These are two independent mechanisms, and together they make a container. cgroups (control groups) handle HOW MUCH: how much CPU, memory and I/O a group of processes gets - so one service cannot eat the whole machine. namespaces handle WHAT IS VISIBLE: a process in its own namespace sees only its own processes, its own network, its own filesystem, as if it were alone on the machine. Docker and systemd are not 'magic': they just set up the kernel's cgroups and namespaces. That is why inside a container ps shows only its processes.

Common mistakes

free inside a container shows the host's memory, not the group's limit. With docker run -m 256m the free -h line still says total 11Gi, because free reads /proc/meminfo, which is not tied to a cgroup. The real limit sits in /sys/fs/cgroup/memory.max: 268435456 bytes, those very 256 MiB. nproc lies the same way - it counted 10 cores where cpu.max allows 50000 100000, that is half a core.

When a process hits its cgroup memory limit, the kernel kills it and leaves little behind. The terminal shows only bash: line 1: 7 Killed python3 -c ... and exit code 137, and the program's own log is empty: it never gets to write anything. Read the group's counters instead - cat /sys/fs/cgroup/memory.events shows the line oom_kill 1.

A fresh network namespace is empty. unshare -n ip -br addr shows a single interface, lo DOWN: no address, no route, and any attempt to reach the outside answers ping: connect: Network is unreachable. Network has to be carried into the namespace: Docker and systemd create a veth pair and add a route, and by hand you do it with ip link add ... type veth and ip netns.

In the book

This topic is covered in full in the chapter Kernel internals and tuning.

See also

The /proc filesystem, Viewing processes, Services: systemctl.