cgroups: What a Process Can Use
A new version of quicknotes has a memory leak. Every hour it grabs more RAM, and soon every other app on the server slows to a crawl. Namespaces kept its view private, but nothing stopped it eating the whole machine. That is the job of control groups, or cgroups.
The rule
Namespaces limit what you see; cgroups limit what you use.
A cgroup is a kernel feature that puts processes into a group and then caps and measures that group's resources: CPU time, memory, the number of processes, disk input/output. Docker creates a cgroup for every container and turns docker run flags into cgroup settings:
docker run -d --name notes \
--memory=256m \
--cpus=0.5 \
--pids-limit=100 \
quicknotes:1.0--memory=256m: the container may use at most 256 MB of RAM. If it tries to go past that, the kernel's out-of-memory (OOM) killer stops a process inside it. When the main process is killed, the container exits, typically with code 137.--cpus=0.5: at most half of one CPU's time. Unlike memory, going over is not fatal; the process is simply slowed down.--pids-limit=100: at most 100 processes, which stops a runaway loop from spawning thousands.
With no flags, there are no limits: a container can use as much CPU and memory as the host will give it. To watch live usage against the limits:
docker stats notesThe shortcut
Sort every isolation question into one of two buckets: "see" → namespace, "use" → cgroup. Then pick the right flag.
Which bucket?
The problem is how much memory it consumes, not what it can see. Bucket: use. So cgroups.
A limit contains a problem; it does not fix it. Pair it with a restart policy and, more importantly, a bug fix.
Drills
Answer fast — trust the rule.
Which Linux feature enforces --memory=256m on a container?
What does --cpus=0.5 mean?
A container with --memory=256m tries to use 400 MB. What typically happens?
You start a container with no resource flags. How much memory may it use?
Remember
- Namespaces limit what you see; cgroups limit what you use.
- Shortcut: "see" → namespace, "use" → cgroup; then
--memory,--cpus,--pids-limit. - Trap: no flags means no limits, and going over memory ends in the OOM killer (exit 137).
