Linux Containers by Hand. Part 5: Limiting process resources with cgroup v2
All parts of the series “Linux Containers by Hand”In Part 1 nerdctl translated --memory and --cpus into memory.max and cpu.max. In Part 2 runc wrote those files using linux.resources from config.json. The container we built with shell commands in Part 3 stayed in the SSH session’s group without its own limits. Today we will create a group in /sys/fs/cgroup, limit memory, CPU, process count, and disk write speed, then run the container from Part 3 in it.
The script for running a command in a group with limits is in the linux-containers-by-hand repository.
Lab setup
| Item | Value |
|---|---|
| Machine | lincont-lab.example.com, 192.168.10.31, Hyper-V VM with 4 vCPUs, 8 GB RAM, and disk sda |
| OS | Ubuntu Server 26.04.1, kernel 7.0.0, systemd 259 |
| containerd and nerdctl | 2.4.2, used only for the image files at the end |
| Image | docker.io/library/alpine:3.24 |
Run all commands as root (sudo -i).
How cgroup v2 works
A control group, or cgroup, is a kernel mechanism for grouping processes, accounting for their resource use, and limiting it. The interface is a filesystem. Directories are groups, subdirectories are child groups, and files are settings and counters. In v2, a single hierarchy covers all resources and each process belongs to exactly one group. A controller handles each kind of resource, such as cpu, memory, io, or pids.
cg=/sys/fs/cgroup
cat $cg/cgroup.controllers
cat $cg/cgroup.subtree_control
ls -d $cg/*/
cat /proc/self/cgroup
cpuset cpu io memory hugetlb pids rdma misc dmem
cpuset cpu io memory hugetlb pids rdma misc dmem
/sys/fs/cgroup/default/
/sys/fs/cgroup/dev-hugepages.mount/
/sys/fs/cgroup/dev-mqueue.mount/
/sys/fs/cgroup/init.scope/
/sys/fs/cgroup/proc-sys-fs-binfmt_misc.mount/
/sys/fs/cgroup/sys-fs-fuse-connections.mount/
/sys/fs/cgroup/sys-kernel-config.mount/
/sys/fs/cgroup/sys-kernel-debug.mount/
/sys/fs/cgroup/sys-kernel-tracing.mount/
/sys/fs/cgroup/system.slice/
/sys/fs/cgroup/user.slice/
0::/user.slice/user-1000.slice/session-82.scope
cgroup.controllerslists available controllers, andcgroup.subtree_controllists those enabled for the group’s children. All are enabled at the root.- systemd builds the tree.
init.scopecontains systemd itself,system.slicecontains services,user.slicecontains user sessions, and*.mountgroups correspond to mounts.defaultis from the earlierctrcontainers. containerd groups them under its namespace name. - Our shell is in the SSH session’s
session-82.scope.
Create a group
Use mkdir to create the group. The kernel populates the directory.
mkdir $cg/lab
ls $cg/lab | wc -l
ls $cg/lab | grep '^cgroup\.' | paste -sd' '
cat $cg/lab/cgroup.controllers
cat $cg/lab/cgroup.subtree_control
cat $cg/lab/cgroup.type
86
cgroup.controllers cgroup.events cgroup.freeze cgroup.kill cgroup.max.depth cgroup.max.descendants cgroup.pressure cgroup.procs cgroup.stat cgroup.stat.local cgroup.subtree_control cgroup.threads cgroup.type
cpuset cpu io memory hugetlb pids rdma misc dmem
domain
There are 86 files. The names beginning with cgroup. appear in every group.
cgroup.procslists member PIDs. Writing a PID moves that process into the group.cgroup.eventsreports whether the group has processes (populated) and whether it is frozen (frozen).cgroup.freezeandcgroup.killfreeze or kill all processes in the group.cgroup.subtree_controlis empty, so children receive no controllers yet.
The other files belong to controllers enabled in the parent, including memory.*, cpu.*, io.*, and pids.*.
Enable four controllers for the children of lab and create a child called c5.
echo '+memory +cpu +pids +io' > $cg/lab/cgroup.subtree_control
cat $cg/lab/cgroup.subtree_control
mkdir $cg/lab/c5
cat $cg/lab/c5/cgroup.controllers
ls $cg/lab/c5 | grep -c '^memory\.'
cpu io memory pids
cpu io memory pids
21
Processes live at the leaves
Try moving a process into lab, which has enabled controllers for its children, and then into c5.
sleep 1000 &
s=$!
echo $s > $cg/lab/cgroup.procs
echo $s > $cg/lab/c5/cgroup.procs
cat $cg/lab/c5/cgroup.procs
cat /proc/$s/cgroup
echo '+memory' > $cg/lab/c5/cgroup.subtree_control
kill $s
[1] 10818
-bash: echo: write error: Device or resource busy
10818
0::/lab/c5
-bash: echo: write error: Device or resource busy
This is cgroup v2’s no-internal-process constraint. A group that distributes these controllers to children cannot contain processes. lab rejected the move, and now that c5 contains a process, it cannot enable a controller for children. Limiting groups this way avoids mixing competition from a group’s own processes with competition from its child groups. The root is exempt.
Writing a PID to cgroup.procs moves a single process. Its future children are born in the same group. For the following examples, a new bash writes its PID ($$) to cgroup.procs before running the workload. Our interactive shell stays outside.
Memory
echo 64M > $cg/lab/c5/memory.max
echo 0 > $cg/lab/c5/memory.swap.max
cat $cg/lab/c5/memory.max $cg/lab/c5/memory.swap.max
bash -c "echo \$\$ > $cg/lab/c5/cgroup.procs; x=aaaaaaaaaaaaaaaa; while :; do x=\$x\$x; done"
echo "exit $?"
cat $cg/lab/c5/memory.events
cat $cg/lab/c5/memory.peak
journalctl -k -o cat --since -1min | grep -E 'Memory cgroup|Killed process' | tail -2
67108864
0
Killed
exit 137
low 0
high 0
max 35
oom 1
oom_kill 1
oom_group_kill 0
sock_throttled 0
67108864
Memory cgroup min protection 0kB -- low protection 0kB
Memory cgroup out of memory: Killed process 10824 (bash) total-vm:116844kB, anon-rss:65652kB, file-rss:3700kB, shmem-rss:0kB, UID:0 pgtables:192kB oom_score_adj:0
memory.max accepts suffixes and stores bytes. Setting memory.swap.max to 0 prevents the workload from spilling into swap. The shell doubles a string until it hits the limit. The kernel tries to reclaim memory in the group, incrementing max in memory.events. When it cannot reclaim enough, it invokes the group’s OOM killer (oom 1, oom_kill 1). SIGKILL produces exit status 137. memory.peak records the group’s lifetime peak, exactly 64 MiB.
Memory also has softer settings. Above memory.high, the kernel throttles the group and aggressively reclaims its memory without invoking the OOM killer. memory.low and memory.min protect a group’s memory from reclaim under pressure.
CPU
Quota with cpu.max
cpu.max has two numbers, the allowed CPU time per period and the length of the period, both in microseconds. Run four infinite loops and measure how many cores’ worth of CPU time they get at different quotas. usage_usec in cpu.stat records time used. cgroup.kill stops all the group’s processes at once.
cat $cg/lab/c5/cpu.max $cg/lab/c5/cpu.weight
(
for max in max "100000 100000" "50000 100000"; do
echo "$max" > $cg/lab/c5/cpu.max
bash -c "echo \$\$ > $cg/lab/c5/cgroup.procs; for i in 1 2 3 4; do (while :; do :; done) & done; wait" &
sleep 2
a=$(awk '/usage_usec/{print $2}' $cg/lab/c5/cpu.stat); sleep 5; b=$(awk '/usage_usec/{print $2}' $cg/lab/c5/cpu.stat)
echo "cpu.max: $max; cores used: $(awk "BEGIN{printf \"%.2f\", ($b-$a)/5000000}")"
echo 1 > $cg/lab/c5/cgroup.kill
wait
done
) 2> /dev/null
grep -E 'nr_periods|nr_throttled|throttled_usec' $cg/lab/c5/cpu.stat
echo max > $cg/lab/c5/cpu.max
max 100000
100
cpu.max: max; cores used: 4.00
cpu.max: 100000 100000; cores used: 1.00
cpu.max: 50000 100000; cores used: 0.50
nr_periods 142
nr_throttled 142
throttled_usec 45762166
Parentheses run the loop in a separate shell so interactive bash does not print background job notices. Without a quota the loops used four cores. 100000 100000 means 100 ms per 100 ms, or one core. 50000 100000 is half a core. nr_throttled counts periods in which the group ran out of quota and had to wait. throttled_usec gives the total time spent throttled. These loops always want more, so the group was throttled every period.
Relative share with cpu.weight
cpu.weight distributes CPU time when groups compete for it. Create two groups with weights 100 and 300 and start one loop in each. taskset -c 0 pins both to the first core so they share it.
mkdir $cg/lab/a $cg/lab/b
echo 100 > $cg/lab/a/cpu.weight
echo 300 > $cg/lab/b/cpu.weight
(
for g in a b; do
bash -c "echo \$\$ > $cg/lab/$g/cgroup.procs; exec taskset -c 0 sh -c 'while :; do :; done'" &
done
sleep 2
a1=$(awk '/usage_usec/{print $2}' $cg/lab/a/cpu.stat); b1=$(awk '/usage_usec/{print $2}' $cg/lab/b/cpu.stat)
sleep 5
a2=$(awk '/usage_usec/{print $2}' $cg/lab/a/cpu.stat); b2=$(awk '/usage_usec/{print $2}' $cg/lab/b/cpu.stat)
awk "BEGIN{printf \"a: %.0f%% b: %.0f%%\n\", ($a2-$a1)/50000, ($b2-$b1)/50000}"
echo 1 > $cg/lab/a/cgroup.kill; echo 1 > $cg/lab/b/cgroup.kill
wait
) 2> /dev/null
rmdir $cg/lab/a $cg/lab/b
a: 25% b: 75%
The core is split in a 100-to-300 ratio. If the second group did not need CPU time, the first would get the entire core. Weights apply only during contention.
Process count
pids.max limits processes and threads in the group. It protects against a fork bomb, a program that spawns processes until the whole system runs out.
echo 10 > $cg/lab/c5/pids.max
bash -c "echo \$\$ > $cg/lab/c5/cgroup.procs; for i in \$(seq 20); do sleep 30 & done; echo started; cat $cg/lab/c5/pids.current" 2>&1
cat $cg/lab/c5/pids.events
echo 1 > $cg/lab/c5/cgroup.kill; sleep 1
cat $cg/lab/c5/pids.current
echo max > $cg/lab/c5/pids.max
bash: fork: retry: Resource temporarily unavailable
bash: fork: retry: Resource temporarily unavailable
bash: fork: retry: Resource temporarily unavailable
bash: fork: retry: Resource temporarily unavailable
bash: fork: Resource temporarily unavailable
max 5
0
Nine sleep processes plus bash make ten. The kernel rejected the fork() that would create the eleventh. bash retried several times and exited with an error. max in pids.events counts hits on the limit, five here. cgroup.kill killed the remaining sleep processes.
Freeze a group
cgroup.freeze suspends all processes without terminating them. This is how docker pause works. Start a counter that writes a new value to a file every 0.1 seconds.
(
bash -c "echo \$\$ > $cg/lab/c5/cgroup.procs; exec sh -c 'i=0; while :; do i=\$((i+1)); echo \$i > /tmp/c5.counter; sleep 0.1; done'" &
sleep 1
echo 1 > $cg/lab/c5/cgroup.freeze
sleep 0.5
cat $cg/lab/c5/cgroup.events
a=$(cat /tmp/c5.counter); sleep 2; b=$(cat /tmp/c5.counter); echo "frozen: $a -> $b"
echo 0 > $cg/lab/c5/cgroup.freeze
a=$(cat /tmp/c5.counter); sleep 2; b=$(cat /tmp/c5.counter); echo "thawed: $a -> $b"
echo 1 > $cg/lab/c5/cgroup.kill; sleep 1; wait
cat $cg/lab/c5/cgroup.events
) 2> /dev/null
rm /tmp/c5.counter
populated 1
frozen 1
frozen: 10 -> 10
thawed: 11 -> 30
populated 0
frozen 0
The counter stops while the group is frozen and continues after thawing. After cgroup.kill, populated 0 confirms it is empty.
Disk I/O
io.max limits reads and writes on a particular disk. Identify the whole disk by its major and minor device numbers, as with /dev nodes. Find the disk backing the root filesystem and cap writes at 10 MB/s.
dev=$(lsblk -no PKNAME $(findmnt -no SOURCE /))
mm=$(cat /sys/block/$dev/dev)
echo "$dev $mm"
echo "$mm wbps=10485760" > $cg/lab/c5/io.max
cat $cg/lab/c5/io.max
mkdir -p /srv/c5
bash -c "echo \$\$ > $cg/lab/c5/cgroup.procs; exec dd if=/dev/zero of=/srv/c5/file bs=1M count=50 oflag=direct" 2>&1 | tail -1
dd if=/dev/zero of=/srv/c5/file2 bs=1M count=50 oflag=direct 2>&1 | tail -1
grep "^$mm" $cg/lab/c5/io.stat
echo "$mm wbps=max" > $cg/lab/c5/io.max
rm -rf /srv/c5
sda 8:0
8:0 rbps=max wbps=10485760 riops=max wiops=max
52428800 bytes (52 MB, 50 MiB) copied, 5.00042 s, 10 MB/s
52428800 bytes (52 MB, 50 MiB) copied, 0.102212 s, 514 MB/s
8:0 rbytes=0 wbytes=52428800 rios=0 wios=100 dbytes=0 dios=0
Writing 50 MiB took exactly five seconds in the group and a tenth of a second outside. oflag=direct matters because buffered writes enter the page cache first. The limit would then apply later, when the kernel writes the cache back to disk. You can limit bytes per second (rbps, wbps) and operations per second (riops, wiops).
Put a container in the group
Return to the container from Part 3. container.sh creates namespaces and switches roots. We will put it in the group ourselves, using the same technique. Get the Alpine root with nerdctl export.
img=docker.io/library/alpine:3.24
mkdir -p /srv/c5/rootfs
id=$(nerdctl create $img)
nerdctl export $id | tar -C /srv/c5/rootfs -xf -
nerdctl rm $id > /dev/null
grep oom_kill $cg/lab/c5/memory.events
bash -c "echo \$\$ > $cg/lab/c5/cgroup.procs; exec ./container.sh /srv/c5/rootfs sh -c 'cat /proc/self/cgroup; x=aaaaaaaaaaaaaaaa; while :; do x=\$x\$x; done'"
echo "exit $?"
grep oom_kill $cg/lab/c5/memory.events
journalctl -k -o cat --since -1min | grep 'Killed process' | tail -1
rm -rf /srv/c5
nerdctl rmi $img > /dev/null
oom_kill 1
0::/
Killed
exit 137
oom_kill 2
Memory cgroup out of memory: Killed process 10989 (sh) total-vm:99964kB, anon-rss:64928kB, file-rss:920kB, shmem-rss:0kB, UID:0 pgtables:184kB oom_score_adj:0
The container sees its group as the root (0::/) because we created the cgroup namespace after moving the process into c5. The 64 MiB limit still applies. The kernel killed sh inside the container and incremented the group’s oom_kill counter.
How systemd does it
On a systemd machine, systemd manages the cgroup tree and may not expect manually created groups in arbitrary places. Use systemd-run to create a temporary group for your process. Its properties have different names and map to the same files.
(systemd-run --scope -p MemoryMax=64M -p TasksMax=10 --unit lab-demo sleep 30 &)
sleep 1
systemctl status lab-demo.scope --no-pager | head -8
cat $cg/system.slice/lab-demo.scope/memory.max $cg/system.slice/lab-demo.scope/pids.max
systemctl stop lab-demo.scope
Running as unit: lab-demo.scope; invocation ID: 05f1519574194753ba1bf19d7cac42df
● lab-demo.scope - [systemd-run] /usr/bin/sleep 30
Loaded: loaded (/run/systemd/transient/lab-demo.scope; transient)
Transient: yes
Active: active (running) since Tue 2026-11-10 20:21:01 UTC; 998ms ago
Invocation: 05f1519574194753ba1bf19d7cac42df
Tasks: 1 (limit: 10)
Memory: 1.7M (max: 64M, available: 62.2M, peak: 1.7M)
CPU: 1ms
67108864
10
MemoryMax became memory.max, and TasksMax became pids.max. This is how nerdctl worked in Part 1. With its systemd driver, it asked systemd for nerdctl-<ID>.scope. The containerd unit uses Delegate=yes so it can manage groups in its own delegated subtree.
Clean up
Remove groups with rmdir after removing their processes and child groups.
rmdir $cg/lab
rmdir $cg/lab/c5 && rmdir $cg/lab
ls -d $cg/lab
rmdir: failed to remove '/sys/fs/cgroup/lab': Device or resource busy
ls: cannot access '/sys/fs/cgroup/lab': No such file or directory
The kernel removes the interface files with the directory. They cannot be deleted individually.
Run with limits using a script
run-limited.sh creates /sys/fs/cgroup/lab/run-<PID>, applies limits, runs the command, prints the kernel counters, and removes the group.
./run-limited.sh -m 64M -- bash -c 'x=aaaaaaaaaaaaaaaa; while :; do x=$x$x; done'
exit code: 137
memory: peak 67108864, oom_kill 1
cpu: usage_usec 165308 nr_throttled 0
pids: peak 1, refused forks 0
-c 0.5 limits CPU time to half a core, and -p 20 caps the process count. The command can be container.sh from Part 3.
References
- Interface files, the no-internal-process constraint, the
memory,cpu,pids, andiocontrollers, and freezing. Control Group v2 - cgroups(7) and cgroup_namespaces(7)
MemoryMax,TasksMax, andDelegate. systemd.resource-control- systemd-run(1) and taskset(1)
Next, we connect a container to the host with a veth pair and a bridge and give it internet access through NAT, doing the work of the CNI bridge plugin by hand.
Only registered users can leave a comment.
Sign in or register to leave a comment.