Skip to content
systemcoding.dev
Systems Programming

The Complete Guide to Linux Namespaces and cgroups for Programmers

Build container isolation by hand: Linux namespaces for what a process sees, cgroups v2 for what it may use, with C code for clone and pivot_root.

29 min read
Summarize in AI
Flat illustration of guest machines running on a hypervisor over hardware, with the Linux, QEMU and C logos.

Docker, Podman, Kubernetes and every other container system do two things to a process, and both are ordinary Linux kernel features that a C program can use directly. First, they change what the process can see: its own process list, network stack, hostname, mounts and users. Those are namespaces. Second, they change what the process can use: a ceiling on memory, CPU, process count and disk bandwidth. Those are control groups, cgroups. Add dropped capabilities and a seccomp filter, and you have a container. Knowing the two mechanisms directly turns container behavior from folklore into something you can read, predict and debug.

"A namespace changes the answer to 'what is there', a cgroup changes the answer to 'how much may this process take', and a container is only a process that got a different answer to both."

This guide covers the subject end to end for C programs on Linux 6.12 with glibc 2.40 and GCC 14: the three system calls that create and join namespaces, each of the eight namespace types with a working example, the cgroup v2 filesystem and its memory, CPU, process and I/O controllers, a complete miniature container runtime in about a hundred lines, and the places where this model is not enough. The code is written against namespaces(7), cgroups(7), clone(2), unshare(2), setns(2) and pivot_root(2), and the programs mostly need root, or a user namespace, to run. Each topic has a focused post in this series, and this guide is written so that you can stop after any section with a working answer.

The mental model

Two questions describe the whole subject. What can this process see? And what may this process consume? The first is answered by the process's namespaces, which are references to kernel objects that wrap a global resource. The second is answered by the process's membership in a cgroup, a node in a tree where each node carries limits and accounting. They are independent. A process can be in a new PID namespace with no limits at all, or inside a tightly limited cgroup while seeing the whole system.

The table shows the division, and the rest of the guide fills in each row.

MechanismControlsExample effectKernel interface
NamespacesThe view of a global resourceThe process sees itself as PID 1 and has its own network interfacesclone, unshare, setns, /proc/<pid>/ns/
cgroupsConsumption of a resourceThe process is killed if it uses more than 256 MiBThe cgroup2 filesystem, usually at /sys/fs/cgroup
CapabilitiesWhich privileged operations are allowedThe process cannot load a kernel modulecapset, prctl
seccompWhich system calls are allowedThe process cannot call ptraceseccomp, prctl

Isolation is the sum of all four. Namespaces and cgroups alone leave a root process in a container with every system call and most capabilities, and no one should call that a sandbox.

Three system calls

A process joins a namespace by being created in it or by moving into it, and three system calls cover every case.

clone(2) creates a new process. With a CLONE_NEW* flag, the child starts in a new namespace of that type, and the glibc wrapper takes a function to run, a stack for the child and the flags. The newer clone3(2), added in Linux 5.3, takes a structure and is what runtimes use now, though glibc has no wrapper and it is called through syscall.

unshare(2) moves the calling process out of the namespaces it shares and into new ones, with no child. One catch matters later: unshare(CLONE_NEWPID) does not move the caller itself, it only makes the next child the first process in a new PID namespace.

setns(2) joins an existing namespace, given a file descriptor opened from /proc/<pid>/ns/<type>. It is how nsenter and docker exec get inside a running container.

The flags, with the kernel version that added each namespace:

FlagNamespaceIsolatesSince
CLONE_NEWNSMountThe set of mount points2.4.19
CLONE_NEWUTSUTSHostname and domain name2.6.19
CLONE_NEWIPCIPCSystem V IPC and POSIX message queues2.6.19
CLONE_NEWPIDPIDProcess ID numbers2.6.24
CLONE_NEWNETNetworkDevices, addresses, routes, firewall, ports2.6.24
CLONE_NEWUSERUserUser and group IDs, capabilities3.8
CLONE_NEWCGROUPCgroupThe apparent root of the cgroup tree4.6
CLONE_NEWTIMETimeOffsets for CLOCK_MONOTONIC and CLOCK_BOOTTIME5.6

A namespace lives as long as a process is in it or something holds a reference. The usual reference is a bind mount of the /proc/<pid>/ns/<type> file onto a regular file, which is how ip netns add keeps a network namespace alive with no process inside it. Unprivileged creation of every type except the user namespace needs CAP_SYS_ADMIN, and the user namespace is the way around that.

The inspection tools

Before writing any code, learn to look. Every process's namespaces are links in /proc/<pid>/ns/, and equal inode numbers mean a shared namespace. The lsns command lists them system wide, and unshare and nsenter from util-linux 2.40 are command line front ends to the system calls above.

Shell
sudo unshare --uts --pid --fork --mount-proc bash -c 'hostname demo; hostname; echo "my pid is $$"; ps -o pid,comm'
Text
demo
my pid is 1
    PID COMMAND
      1 bash
      2 ps

The command made a new UTS namespace, set the hostname inside it, and made a new PID namespace in which the shell is PID 1. The --fork flag is needed because unshare itself stays in the old PID namespace and only its child enters the new one. The --mount-proc flag makes a private mount namespace and remounts /proc, so ps sees only the new namespace's processes. If you leave it out, ps still reads the host's /proc and lists every host process, which is the single most common source of confusion with PID namespaces.

UTS and IPC: the simple ones

The UTS namespace gives a process its own hostname and NIS domain name, and nothing else. The IPC namespace gives it its own System V semaphores, message queues, shared memory segments and POSIX message queues. Both are cheap and rarely cause trouble. The earlier post in this series on what namespaces are shows the UTS case in C. One consequence of the IPC namespace is worth stating plainly: two containers that need to share memory through System V keys or /dev/mqueue messages must share an IPC namespace explicitly, and a bug report that says "the queue is empty" in a container is often this.

PID namespaces

A PID namespace gives its processes a separate numbering. The first process in it has PID 1, and it is special: it is the namespace's init. When it exits, the kernel kills every other process in the namespace. It receives orphaned children and is expected to reap them with wait, and it gets no default signal handlers: a signal such as SIGTERM sent from inside the namespace to PID 1 is ignored unless PID 1 installed a handler, which is why a container whose main process is a shell script sometimes refuses to stop on docker stop until the timeout sends SIGKILL.

Every process also has a PID in each ancestor namespace, so the same process shows PID 1 inside and a large number from the host. The code below creates a child in a new PID namespace and has both sides report:

pidns.cc
#define _GNU_SOURCE
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024)

static int child_main(void *arg)
{
    (void)arg;
    printf("inside:  pid=%d ppid=%d\n", getpid(), getppid());
    return 0;
}

int main(void)
{
    char *stack = mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE,
                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
    if (stack == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    pid_t pid = clone(child_main, stack + STACK_SIZE, CLONE_NEWPID | SIGCHLD, NULL);
    if (pid == -1) {
        perror("clone");
        return 1;
    }
    printf("outside: child pid=%d\n", pid);

    waitpid(pid, NULL, 0);
    return 0;
}
Shell
gcc -std=gnu17 -O2 -Wall -o pidns pidns.c
sudo ./pidns
Text
outside: child pid=18522
inside:  pid=1 ppid=0

The child sees itself as PID 1 and its parent as 0, because the parent is in a different namespace and has no number there. The child's host PID varies per run. The stack grows down on x86-64, so clone takes the highest address of the region, which is why the call passes stack + STACK_SIZE. The SIGCHLD flag makes the termination signal the usual one, so waitpid works as for a fork.

If this child ran ps it would still list the host's processes, because /proc is a mount of the host's view. A new PID namespace needs a new mount of proc inside a new mount namespace for tools to agree, which is the subject of the next section.

Mount namespaces and pivot_root

A mount namespace gives a process its own set of mount points. The child starts with a copy of its parent's mounts, and from then on changes made in either do not appear in the other, unless the kernel's propagation rules say otherwise. That detail is the main trap: on systems with systemd, the root mount is shared, which means a mount made in the new namespace can propagate back to the host. Before doing anything else, a new mount namespace must make its mounts private:

private_mounts.cc
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/mount.h>

int make_mounts_private(void)
{
    if (mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL) == -1) {
        fprintf(stderr, "make private: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

MS_REC | MS_PRIVATE applied to / marks every mount in the namespace private, so nothing leaks. Skipping this step is how a container runtime that mounts proc inside the namespace accidentally changes the host's /proc mount, a bug that has happened more than once in real software.

To give the process its own root filesystem, the correct call is pivot_root(2), not chroot. chroot only changes where the process starts path lookups, and a root process can escape it. pivot_root swaps the root mount of the whole namespace and lets you detach the old root, leaving nothing behind to reach. glibc has no wrapper, so call it with syscall. The new root must be a mount point, so bind mount it onto itself first, and the old root is moved to a directory under the new one:

pivot.cc
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>

static int pivot_into(const char *new_root)
{
    if (mount(new_root, new_root, NULL, MS_BIND | MS_REC, NULL) == -1)
        return -1;
    if (chdir(new_root) == -1)
        return -1;

    mkdir("put_old", 0700);
    if (syscall(SYS_pivot_root, ".", "put_old") == -1)
        return -1;
    if (chdir("/") == -1)
        return -1;

    if (umount2("/put_old", MNT_DETACH) == -1)
        return -1;
    return rmdir("/put_old");
}

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "usage: %s new_root\n", argv[0]);
        return 2;
    }
    if (pivot_into(argv[1]) == -1) {
        fprintf(stderr, "pivot failed: %s\n", strerror(errno));
        return 1;
    }
    puts("the old root is gone");
    return 0;
}
Text
pivot failed: Operation not permitted

Run as an ordinary user, the program fails with EPERM, because mount needs privilege in the mount namespace, as shown. It is meant to be used inside a mount namespace created by the program in the next sections, where it succeeds and pivot_root leaves the process with the directory it was given as /. MNT_DETACH performs a lazy unmount so the old root disappears even if something still uses it. The process now cannot name any file outside the new root, which no amount of .. can change.

User namespaces: root without privilege

The user namespace is the enabling piece. It maps user and group IDs inside the namespace to different IDs outside, so a process can be UID 0, root, inside while being an ordinary UID on the host. Inside, it holds a full capability set, but those capabilities apply only to resources owned by the new user namespace, including the other namespaces it creates. It does not hold power over the host: it cannot load kernel modules, change the host's clock or read the host's files that its mapped UID cannot read.

Creating one needs no privilege, which is what makes rootless containers possible. The mapping has to be written by hand through /proc/<pid>/uid_map and gid_map, each line having the form inside_id outside_id count. An unprivileged process may write only a single line mapping its own UID, and must first write deny to /proc/<pid>/setgroups before it can write the group map.

userns.cc
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static int write_file(const char *path, const char *text)
{
    int fd = open(path, O_WRONLY);
    if (fd == -1)
        return -1;
    ssize_t n = write(fd, text, strlen(text));
    close(fd);
    return n == (ssize_t)strlen(text) ? 0 : -1;
}

int main(void)
{
    uid_t uid = getuid();
    gid_t gid = getgid();

    if (unshare(CLONE_NEWUSER) == -1) {
        perror("unshare");
        return 1;
    }

    char map[64];
    write_file("/proc/self/setgroups", "deny");
    snprintf(map, sizeof map, "0 %u 1", (unsigned)uid);
    if (write_file("/proc/self/uid_map", map) == -1) {
        perror("uid_map");
        return 1;
    }
    snprintf(map, sizeof map, "0 %u 1", (unsigned)gid);
    if (write_file("/proc/self/gid_map", map) == -1) {
        perror("gid_map");
        return 1;
    }

    printf("uid inside: %u (outside it is %u)\n", getuid(), (unsigned)uid);

    FILE *f = fopen("/proc/self/status", "r");
    char line[128];
    while (f != NULL && fgets(line, sizeof line, f) != NULL)
        if (strncmp(line, "CapEff:", 7) == 0)
            fputs(line, stdout);
    if (f != NULL)
        fclose(f);
    return 0;
}
Shell
gcc -std=gnu17 -O2 -Wall -o userns userns.c
./userns
Text
uid inside: 0 (outside it is 1001)
CapEff:	000001ffffffffff

An ordinary user becomes UID 0 and gains every capability, yet all of them are scoped to the new user namespace. Any file the kernel checks against the host's UID 1001 is still accessed as 1001, and a file owned by host root shows its owner as nobody (65534) inside, because that owner has no mapping. The mapping is the entire trick.

Some distributions restrict unprivileged user namespaces because they expose a large amount of kernel code to unprivileged users, which has produced vulnerabilities. If unshare returns EPERM, look at sysctl kernel.unprivileged_userns_clone on Debian derived kernels, user.max_user_namespaces, and the AppArmor restriction setting on recent Ubuntu releases. A rootful runtime does not need any of this.

Network namespaces

A network namespace has its own interfaces, addresses, routing tables, firewall rules and port numbers. A fresh one contains only a loopback device, and it is down. Everything else, a virtual interface pair to talk to the host, addresses and routes, must be created. The program below makes a new network namespace and lists the interfaces it sees, using if_nameindex and not /sys/class/net, because the sysfs mount is bound to the namespace it was mounted in and would still show the host's devices.

netns.cc
#define _GNU_SOURCE
#include <net/if.h>
#include <sched.h>
#include <stdio.h>

static void list_interfaces(const char *label)
{
    struct if_nameindex *list = if_nameindex();
    printf("%s:", label);
    for (struct if_nameindex *i = list; i != NULL && i->if_index != 0; i++)
        printf(" %s", i->if_name);
    printf("\n");
    if_freenameindex(list);
}

int main(void)
{
    list_interfaces("before");
    if (unshare(CLONE_NEWUSER | CLONE_NEWNET) == -1) {
        perror("unshare");
        return 1;
    }
    list_interfaces("after ");
    return 0;
}
Text
before: lo enp3s0 docker0
after : lo

The host shows three interfaces in this example, and the new namespace shows only lo. The combined CLONE_NEWUSER | CLONE_NEWNET flags work for an unprivileged user because the kernel creates the user namespace first, which gives the process the capability it needs to create the network namespace. To connect such a namespace to the outside, a runtime creates a veth pair, a virtual Ethernet cable with an end in each namespace, moves one end in by network namespace file descriptor, assigns addresses, and sets up routing and usually network address translation on the host. The shell equivalent, as root:

Shell
sudo ip netns add demo
sudo ip link add veth-host type veth peer name veth-demo
sudo ip link set veth-demo netns demo
sudo ip addr add 10.200.0.1/24 dev veth-host
sudo ip link set veth-host up
sudo ip netns exec demo ip addr add 10.200.0.2/24 dev veth-demo
sudo ip netns exec demo ip link set veth-demo up
sudo ip netns exec demo ping -c 1 10.200.0.1
Text
PING 10.200.0.1 (10.200.0.1) 56(84) bytes of data.
64 bytes from 10.200.0.1: icmp_seq=1 ttl=64 time=0.052 ms

--- 10.200.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms

The latency in the output is an example. A namespace made by ip netns add is kept alive by a bind mount under /run/netns/, which is the reference mechanism described earlier, and ip netns exec calls setns to join it. A program does the same by opening /run/netns/demo and calling setns(fd, CLONE_NEWNET).

The cgroup and time namespaces

The cgroup namespace makes a process see the cgroup it started in as the root of its cgroup tree. Without it, a container reading /proc/self/cgroup sees the full host path such as /system.slice/docker-abc.scope, which leaks host layout. With it, it sees /. It changes only the view of paths, and not limits.

The time namespace gives a process its own offsets for the monotonic and boot clocks, set by writing to /proc/<pid>/timens_offsets before the first process starts in it. It exists so a container that is checkpointed and restored on another host can keep a monotonic clock that continues where it was. It does not touch CLOCK_REALTIME, so a container cannot set a different date this way.

A miniature container

The pieces fit into a program of about a hundred lines. This runtime creates new mount, PID, UTS, IPC and network namespaces, makes mounts private, sets the hostname, pivots into a root filesystem directory you provide (a directory containing a static busybox and the usual bin, proc and dev directories), mounts proc and runs a command. It must run as root, since it does not create a user namespace, and it prints no output of its own so that the command's output is the result.

minirun.cc
#define _GNU_SOURCE
#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024)

struct config {
    const char *rootfs;
    char **argv;
};

static void fail(const char *what)
{
    fprintf(stderr, "minirun: %s: %s\n", what, strerror(errno));
    _exit(1);
}

static int container_main(void *arg)
{
    struct config *cfg = arg;

    if (mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL) == -1)
        fail("make mounts private");
    if (sethostname("minirun", 7) == -1)
        fail("sethostname");

    if (mount(cfg->rootfs, cfg->rootfs, NULL, MS_BIND | MS_REC, NULL) == -1)
        fail("bind root");
    if (chdir(cfg->rootfs) == -1)
        fail("chdir");
    mkdir("put_old", 0700);
    if (syscall(SYS_pivot_root, ".", "put_old") == -1)
        fail("pivot_root");
    if (chdir("/") == -1)
        fail("chdir /");
    if (umount2("/put_old", MNT_DETACH) == -1)
        fail("umount old root");
    rmdir("/put_old");

    if (mount("proc", "/proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL) == -1)
        fail("mount proc");

    char *envp[] = { "PATH=/bin:/usr/bin", "HOME=/root", "TERM=xterm", NULL };
    execve(cfg->argv[0], cfg->argv, envp);
    fail("execve");
    return 1;
}

int main(int argc, char **argv)
{
    if (argc < 3) {
        fprintf(stderr, "usage: %s rootfs command [args...]\n", argv[0]);
        return 2;
    }
    if (geteuid() != 0) {
        fputs("minirun: run as root\n", stderr);
        return 1;
    }

    struct config cfg = { .rootfs = argv[1], .argv = &argv[2] };
    char *stack = mmap(NULL, STACK_SIZE, PROT_READ | PROT_WRITE,
                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
    if (stack == MAP_FAILED) {
        perror("mmap");
        return 1;
    }

    int flags = CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWNET | SIGCHLD;
    pid_t pid = clone(container_main, stack + STACK_SIZE, flags, &cfg);
    if (pid == -1) {
        perror("clone");
        return 1;
    }

    int status = 0;
    waitpid(pid, &status, 0);
    return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}
Shell
gcc -std=gnu17 -O2 -Wall -o minirun minirun.c
sudo ./minirun /srv/rootfs /bin/sh -c 'hostname; echo "pid $$"; ls /proc | head -n 3; ip link 2>/dev/null || echo "no network tools"'
Text
minirun
pid 1
1
2
acpi
no network tools

The shell in the container reports the hostname set by the runtime, PID 1, a /proc that lists only the container's own processes (PID 1 and the ls it only spawned, plus kernel entries such as acpi), and no network beyond lo. The /srv/rootfs path and the tools in it are a choice of the reader's: anything with a static busybox and an empty proc directory works. The program is deliberately incomplete, and the missing parts are the lesson. It has no user namespace, so the shell runs as real root with the host's full capability set. It has no cgroup, so the process may use all the memory. It has no seccomp filter. A root process in this container can still call mknod to create a device node for the host's disk, and read it. Do not run untrusted code in it. What it shows is that the visible container is a few system calls in order, and everything else a runtime does is hardening and plumbing.

Control groups

A control group, cgroup, is a node in a tree. Processes belong to nodes, and each node can carry limits and accounting for a set of resources called controllers. A child process starts in its parent's cgroup. Resource use is counted per node, summed over every process in the subtree, and limits cap the total for the whole subtree.

Linux has two versions. Version 1 had a separate hierarchy per controller, which allowed a process to be in different places in each, and it was hard to reason about. Version 2, the unified hierarchy, has one tree for all controllers, and it is the default on current distributions. Check which one you have with stat:

Shell
stat -fc %T /sys/fs/cgroup
Text
cgroup2fs

If the output is tmpfs you have version 1 or a hybrid layout. This guide uses version 2 only, since new code should target it. A node is a directory under /sys/fs/cgroup, and creating one is mkdir. The files inside it are the interface.

FileRole
cgroup.controllersControllers available in this cgroup, read only
cgroup.subtree_controlControllers enabled for children, written as +memory -io
cgroup.procsPIDs of member processes; writing a PID moves it here
cgroup.eventsWhether the cgroup has live processes, and whether it is frozen
cgroup.killWriting 1 kills every process in the subtree (Linux 5.14)
memory.max, memory.high, memory.currentMemory hard limit, throttle threshold and current use
cpu.max, cpu.weightCPU quota and relative share
pids.max, pids.currentLimit on and count of processes and threads
io.max, io.weightBlock device bandwidth and IOPS limits and shares

Two structural rules cause most errors. A controller must be enabled in the parent's cgroup.subtree_control before the child's control files for it appear. And the "no internal processes" rule says a cgroup that has enabled controllers for its children cannot itself contain processes, except the root. So a process is placed in a leaf, and interior nodes only organize.

Limiting memory

The memory controller has two main limits. memory.max is a hard ceiling: when the cgroup tries to exceed it, the kernel first reclaims cache, and if that fails, kills a process with the out of memory handler. memory.high is a soft threshold: above it, the processes are throttled and forced to reclaim, but not killed, which makes it the right choice for a limit you want to degrade gracefully. Values are in bytes, with the suffixes K, M and G accepted, and max means unlimited. memory.swap.max controls swap and is worth setting to 0 so a limit means what it says.

The program creates a cgroup, sets a 64 MiB limit, puts a child in it, and has the child allocate and touch 128 MiB. The parent reports what happened and prints the cgroup's event counters. It must run as root and assumes no other manager owns that part of the tree.

memlimit.cc
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

#define CG "/sys/fs/cgroup/demo"

static int write_file(const char *path, const char *text)
{
    int fd = open(path, O_WRONLY);
    if (fd == -1) {
        fprintf(stderr, "open %s: %s\n", path, strerror(errno));
        return -1;
    }
    ssize_t n = write(fd, text, strlen(text));
    int saved = errno;
    close(fd);
    if (n != (ssize_t)strlen(text)) {
        fprintf(stderr, "write %s: %s\n", path, strerror(saved));
        return -1;
    }
    return 0;
}

static void child(void)
{
    char pid[32];
    snprintf(pid, sizeof pid, "%d", getpid());
    if (write_file(CG "/cgroup.procs", pid) == -1)
        _exit(1);

    size_t total = 128UL * 1024 * 1024;
    char *p = malloc(total);
    for (size_t i = 0; i < total; i += 4096)
        p[i] = 1;
    puts("child touched 128 MiB without being killed");
    _exit(0);
}

int main(void)
{
    write_file("/sys/fs/cgroup/cgroup.subtree_control", "+memory +pids");
    if (mkdir(CG, 0755) == -1 && errno != EEXIST) {
        perror("mkdir");
        return 1;
    }
    write_file(CG "/memory.max", "67108864");
    write_file(CG "/memory.swap.max", "0");
    write_file(CG "/pids.max", "16");

    pid_t pid = fork();
    if (pid == 0)
        child();

    int status = 0;
    waitpid(pid, &status, 0);
    if (WIFSIGNALED(status))
        printf("child killed by signal %d (%s)\n", WTERMSIG(status), strsignal(WTERMSIG(status)));

    FILE *f = fopen(CG "/memory.events", "r");
    char line[64];
    while (f != NULL && fgets(line, sizeof line, f) != NULL)
        fputs(line, stdout);
    if (f != NULL)
        fclose(f);

    rmdir(CG);
    return 0;
}
Shell
gcc -std=gnu17 -O2 -Wall -o memlimit memlimit.c
sudo ./memlimit
Text
child killed by signal 9 (Killed)
low 0
high 0
max 43
oom 1
oom_kill 1
oom_group_kill 0

The child allocated memory page by page until it crossed 64 MiB, the kernel reclaimed what it could, hit the limit 43 times (the max counter, a number that varies), and killed the child with SIGKILL, which the shell would show as Killed. The oom_kill counter confirms that the kernel's OOM handler did it, and not the program. rmdir removes the cgroup now that it is empty: a cgroup can be deleted only when it has no processes and no child cgroups, and the call fails with EBUSY otherwise.

Two details deserve attention. The allocation touches each page because untouched malloc memory is not charged until it is written. And oom_group_kill relates to memory.oom.group, which, if set to 1, makes the kernel kill all processes in the cgroup together instead of picking one, the right setting for a container where a half dead process tree is worse than a clean restart.

Limiting CPU

cpu.max takes two numbers, a quota and a period, both in microseconds: "50000 100000" means 50,000 microseconds of CPU time in every 100,000 microsecond period, so half of one CPU. A quota of max removes the limit. Quotas can exceed the period for multiple CPUs: "200000 100000" allows two full CPUs. When the group uses up its quota within a period, its processes are throttled until the next period starts, and the file cpu.stat counts how often (nr_throttled, throttled_usec).

cpu.weight is a different idea, a relative share used only when the CPUs are contended. A cgroup with weight 200 gets twice the CPU of a sibling with weight 100 when both want more than is available, and nothing is limited when the machine is idle. Use quotas to cap and weights to share.

Shell
echo "50000 100000" | sudo tee /sys/fs/cgroup/demo/cpu.max
cat /sys/fs/cgroup/demo/cpu.stat | head -n 4
Text
50000 100000
usage_usec 1842260
user_usec 1790014
system_usec 52246
nr_periods 38

The counters are an example. A busy loop inside a cgroup with this quota shows about 50 percent in top and a growing nr_throttled. A throttled service shows latency spikes at period boundaries, which is a known cost of quotas for latency sensitive servers, and a reason to prefer weights unless a hard cap is a requirement.

Limiting processes and I/O

The pids controller limits the number of tasks, processes and threads, in a cgroup. Its job is to stop a fork bomb from taking down the host: once pids.current reaches pids.max, fork and clone return EAGAIN for processes in the cgroup. Set it in every cgroup that runs untrusted or buggy code, and size it generously for threaded programs, since every thread counts.

The io controller limits and weighs block device access. A line in io.max names the device by major and minor number and lists limits: "8:0 rbps=10485760 wbps=5242880 riops=max wiops=max". The device numbers come from lsblk or stat -c %t:%T on the device node. The limit applies to direct I/O and, in cgroup v2 with a recent kernel, to buffered writeback as well, which the older version could not do. Note that it limits throughput for one device, and it does not control a filesystem's space, so disk quotas remain the filesystem's job.

Seeing what a cgroup is doing

Accounting files answer most questions. memory.current and memory.peak (Linux 5.19) give the current and highest usage, memory.stat breaks it into anonymous memory, page cache and kernel memory, cpu.stat has usage and throttling, and pids.current counts tasks. Pressure stall information, the memory.pressure, cpu.pressure and io.pressure files, report the share of time tasks were stalled waiting for that resource, which is a better signal than utilization that a cgroup is too small:

Shell
cat /sys/fs/cgroup/demo/memory.pressure
Text
some avg10=0.00 avg60=0.12 avg300=0.04 total=1893210
full avg10=0.00 avg60=0.03 avg300=0.01 total=502811

some is the percentage of time at least one task was stalled, and full the percentage when all of them were. The numbers are an example. Sustained non zero values of full mean that the workload spends time doing nothing but waiting for memory, and either the limit is too low or the program wastes memory. Which cgroup a process belongs to is in /proc/<pid>/cgroup, a single line 0::/path on version 2.

Working with systemd instead of against it

On most distributions, systemd owns the cgroup tree. It puts every service in its own cgroup under system.slice, every user session under user.slice, and expects to be the only writer. A program that creates cgroups directly under the root, as the examples above do, works on a test machine and fights with systemd on a managed one: systemd may move processes or remove directories it does not know. There are two correct approaches.

The first is to let systemd create the cgroup and set the limits, which is a service property. The command line version is systemd-run, and a unit file expresses the same with MemoryMax=, MemoryHigh=, CPUQuota=, TasksMax= and IOWeight=:

Shell
sudo systemd-run --scope -p MemoryMax=256M -p CPUQuota=50% -p TasksMax=64 ./worker
systemd-cgls --no-pager | head -n 6
Text
Running scope as unit: run-r8f3a9c1d2e0b4a6f.scope
Control group /:
-.slice
├─user.slice
│ └─user-1000.slice
│   ├─session-2.scope

The first line is the unit that systemd-run created, a name that differs per run. The limits in the properties are the same files in the same tree, set by systemd with the same semantics.

The second approach is delegation. A unit with Delegate=yes receives a subtree of the cgroup hierarchy that systemd promises not to touch, and the service, such as a container runtime, may create and manage cgroups inside it freely. That is how Docker, Podman and Kubernetes coexist with systemd. If you write a runtime, ask for delegation, and create your cgroups below the cgroup your own process starts in, which you read from /proc/self/cgroup.

Joining a running container with setns

The third system call is how debugging tools get inside something that already runs. setns(fd, flags) takes a descriptor for a namespace file and moves the calling thread into that namespace, and the flag, if not zero, asserts which type the descriptor must be. The program below enters the network namespace of another process, given its PID, and lists the interfaces it sees there. It needs CAP_SYS_ADMIN, and for a network namespace owned by a user namespace, CAP_SYS_ADMIN in that user namespace as well.

enter_net.cc
#define _GNU_SOURCE
#include <fcntl.h>
#include <net/if.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "usage: %s pid\n", argv[0]);
        return 2;
    }

    char path[64];
    snprintf(path, sizeof path, "/proc/%s/ns/net", argv[1]);
    int fd = open(path, O_RDONLY | O_CLOEXEC);
    if (fd == -1) {
        perror(path);
        return 1;
    }
    if (setns(fd, CLONE_NEWNET) == -1) {
        perror("setns");
        return 1;
    }
    close(fd);

    struct if_nameindex *list = if_nameindex();
    printf("interfaces in the namespace of pid %s:", argv[1]);
    for (struct if_nameindex *i = list; i != NULL && i->if_index != 0; i++)
        printf(" %s", i->if_name);
    printf("\n");
    if_freenameindex(list);
    return 0;
}
Shell
gcc -std=gnu17 -O2 -Wall -o enter_net enter_net.c
sudo ./enter_net 8841
Text
interfaces in the namespace of pid 8841: lo eth0

The pid belongs to an example container process that has a loopback device and one virtual Ethernet end. nsenter --target 8841 --net ip addr does the same from the shell, and docker exec and kubectl exec join the full set of namespaces of the container's init process, plus its cgroup, before running the command. A mount namespace join has one restriction: a multithreaded process cannot call setns for a mount or user namespace, so tools do it in a single threaded helper.

Freezing and killing a whole cgroup

The tree structure gives group operations that individual PIDs cannot. Writing 1 to cgroup.freeze stops every process in the subtree without signals, so they cannot catch or ignore it, and writing 0 thaws them. Writing 1 to cgroup.kill, added in Linux 5.14, sends SIGKILL to every process in the subtree, including ones that fork while it runs, which closes the race that makes a kill loop over PIDs unreliable. Removing a cgroup after killing it is the clean way to end a whole service:

kill_group.cc
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

static int write_text(const char *path, const char *text)
{
    int fd = open(path, O_WRONLY);
    if (fd == -1)
        return -1;
    ssize_t n = write(fd, text, strlen(text));
    close(fd);
    return n == (ssize_t)strlen(text) ? 0 : -1;
}

int main(void)
{
    const char *cg = "/sys/fs/cgroup/demo";

    if (write_text("/sys/fs/cgroup/demo/cgroup.kill", "1") == -1) {
        printf("cgroup.kill: %s\n", strerror(errno));
        return 1;
    }
    usleep(100000);
    if (rmdir(cg) == -1) {
        printf("rmdir: %s\n", strerror(errno));
        return 1;
    }
    puts("cgroup emptied and removed");
    return 0;
}
Text
cgroup emptied and removed

The short sleep gives the kernel time to finish tearing the processes down, since the kill is asynchronous, and rmdir fails with EBUSY while any member remains. A more careful program polls the populated line in cgroup.events until it reads populated 0, or waits on that file with poll, which the kernel wakes when the value changes.

Checking that the isolation is real

Isolation claims deserve a test, because a mistake in one flag leaves a leak that looks fine from inside. Run each check from inside the container and compare with the host. For the PID namespace, ls /proc | grep -c '^[0-9]' should count only the container's processes. For the network namespace, cat /proc/net/dev should list only its own interfaces. For the mount namespace, cat /proc/self/mountinfo should show the new root and not the host's mounts, and ls / should list the image's directories. For the user namespace, cat /proc/self/uid_map shows the mapping, and a root owned host file such as /etc/shadow in a bind mount should appear owned by nobody and be unreadable. For cgroups, cat /proc/self/cgroup and the limit files under /sys/fs/cgroup confirm membership, and the cgroup namespace makes the path read 0::/. And for the capability and seccomp layers, grep -E 'Cap|Seccomp|NoNewPrivs' /proc/self/status shows what is left. A container whose CapEff equals the host root's full mask and whose Seccomp is 0 has namespaces and nothing else.

Security and pitfalls

Several failure patterns recur, and each is a place where the model above is easy to get wrong.

MistakeWhat goes wrongFix
PID 1 is a shell script or an app without signal handlingThe container ignores SIGTERM and zombies pile upRun a small init such as tini or use --init, or handle signals and reap children
New mount namespace without making / privateMounts propagate to the hostRemount / with MS_REC and MS_PRIVATE first
/proc not remounted in a new PID namespaceps shows host processesMount a new proc in a private mount namespace
Using chroot instead of pivot_rootA root process can escapepivot_root and detach the old root
User namespace maps more than neededExtra host IDs become reachableMap only the range required
No memory limit, or memory.max without memory.swap.maxThe container swaps or takes the host's memorySet both, and memory.oom.group
Limit set with RLIMIT_ASAddress space is limited, not memoryUse the memory controller
Creating cgroups under systemd without delegationsystemd moves or deletes themUse systemd-run or Delegate=yes
Treating the container as a security boundaryA kernel bug gives access to the hostAdd seccomp, capabilities, user namespaces, and consider a VM

The last row is the boundary of the whole approach. A container shares the host kernel, so a kernel vulnerability is a container escape, and the layers above reduce the reachable surface without removing it. For running code from untrusted tenants, the usual answer is a lightweight virtual machine, such as Firecracker, or a user space kernel such as gVisor, which put a second boundary between the workload and the host kernel.

When this guide does not fit

This is the Linux model. Other operating systems have different mechanisms: FreeBSD jails, Solaris zones and Windows job objects and silos, and the code here does not carry over. Programs that only need to cap their own resources can use setrlimit and avoid cgroups altogether, as the earlier post on resource limits shows. Programs that need strong isolation of untrusted code need more than the pieces in this guide. And if you want to run containers rather than build a runtime, use an existing one, because getting a runtime right, with image handling, networking, rootless mode and security updates, is a large project that others maintain: runc, crun and youki are the usual low level runtimes, and bubblewrap is a small tool for sandboxing a single command.

A decision table to keep

You needUse
A private hostnameUTS namespace
A process that sees itself as PID 1PID namespace plus a private /proc
A private root filesystemMount namespace, MS_PRIVATE on /, pivot_root
To run as root without host privilegeUser namespace with a one line ID map
An isolated network stackNetwork namespace plus a veth pair
To join a running containersetns on its /proc/<pid>/ns/* files
A hard memory capmemory.max with memory.swap.max set to 0
A soft memory limit that throttlesmemory.high
A CPU capcpu.max; a relative share is cpu.weight
Protection against fork bombspids.max
To manage cgroups on a systemd hostsystemd-run properties or Delegate=yes
Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.