The Complete Guide to Linux Containers From Scratch
Build a working Linux container runtime in C: namespaces, a pivot_root rootfs, cgroup v2 limits, veth networking, seccomp, and what runc adds on top.

A container is not a thing the kernel knows about. There is no container_create system call, no container object in the kernel's data structures and no container ID that the scheduler understands. What exists is a handful of independent kernel features, namespaces, control groups, mounts, capabilities and system call filters, and a container runtime is the program that applies them to one process in the right order. Once you have written that program yourself, Docker, Podman, containerd and Kubernetes stop being mysterious: they are different ways of asking a runtime like runc to repeat what you are about to do by hand.
This guide builds that runtime in C, one feature at a time, with every step testable from a shell. It starts with the root filesystem, adds the namespaces in the order that matters, makes the mount tree safe and pivots into it, places the process in a cgroup with memory, CPU and process limits, gives it a network connection, filters its system calls, and ends with a complete single-file program of about two hundred lines. The later sections explain what the program deliberately leaves out, where it is unsafe, and how runc closes those gaps. The code targets Linux 6.12 on x86-64 with glibc 2.40, GCC 14, libseccomp 2.5 and cgroup v2, and everything runs as root in a disposable machine or virtual machine. Nothing here needs Docker.
What you will build and what you need
The finished program, minic, takes a root filesystem directory and a command, and runs the command as PID 1 inside new mount, PID, UTS, IPC, network and cgroup namespaces, with its own hostname, a private view of /proc, resource limits, a veth connection to the host and a seccomp filter. It is a teaching runtime. It has no image format, no layers, no user namespace support in the main path and none of the safety checks a production runtime needs, and the later sections say which is which.
You need a Linux machine you can break. A virtual machine is best, because the exercises create network interfaces, change forwarding settings and write to the cgroup tree. Check these prerequisites first.
uname -r
stat -fc %T /sys/fs/cgroup
gcc --version | head -n 1
ls /usr/include/seccomp.h6.12.4
cgroup2fs
gcc (GCC) 14.2.1 20250207
/usr/include/seccomp.hThe kernel version and compiler string will differ, but the second line must say cgroup2fs. If it says tmpfs, your distribution is on the old cgroup v1 layout, and the cgroup step needs different file names, which the post on cgroups v1 and v2 in this series lists. If the seccomp header is missing, install the libseccomp development package for your distribution.
What a container really is
Four ideas carry the whole subject, and each one maps to a section of the program.
Namespaces change what a process can see. A process is always in exactly one namespace of each of eight types. Putting it in a new mount namespace gives it its own mount table, a new PID namespace gives it its own process numbering, a new network namespace gives it its own interfaces and routes, and so on. The namespaces post in this series describes all eight in detail. The program uses six of them.
Control groups change what a process can use. A cgroup is a directory in /sys/fs/cgroup, and a process belongs to the one whose cgroup.procs file lists it. Writing numbers into files such as memory.max, cpu.max and pids.max makes the kernel enforce them for every process in the group and its descendants.
A changed root changes where a process looks. Namespaces alone do not give a container its own filesystem, because a new mount namespace starts as a copy of the old one. The runtime must build a directory tree for the container and make it the root, using pivot_root and then detaching the old root so no path leads back to the host.
Restrictions change what a process may do. Dropped capabilities, no_new_privs and a seccomp filter shrink the set of privileged operations and system calls available even to a process that is root inside its namespace. This is what separates a container from a mere chroot with a private process list.
None of these four is a security boundary by itself. Together, and applied carefully, they give the isolation that most of the industry runs production workloads on, with the caveat that every container on a host shares one kernel. The comparison post on microVMs and containers, later in this series, covers when that is not enough.
Step zero: a root filesystem to run in
A container needs a directory that looks like the root of a small Linux system. The easiest way to get one is a static BusyBox, a single executable that provides a shell and the common utilities, with no shared libraries to copy. Debian and Ubuntu ship it as busybox-static, and most other distributions have an equivalent. Build the tree with the minimum directories a shell expects.
mkdir -p rootfs/{bin,proc,sys,dev,etc,tmp,old_root}
cp "$(command -v busybox)" rootfs/bin/busybox
for app in sh ls ps cat id hostname mount echo sleep ip ping; do
ln -sf busybox rootfs/bin/$app
done
echo "root:x:0:0:root:/:/bin/sh" > rootfs/etc/passwd
file rootfs/bin/busybox | cut -d, -f1-3rootfs/bin/busybox: ELF 64-bit LSB executable, x86-64, version 1 (SYSV)file must report a statically linked executable, which you can confirm in the rest of its output. If it says "dynamically linked", copy the shared libraries it needs, which ldd lists, into matching paths under rootfs, or find a static build. The old_root directory is the mount point for the pivot_root step. The symbolic links make BusyBox behave as each named tool, since it chooses its behaviour from the name it was started under.
You can test this directory before involving any namespaces, with chroot, which is the weakest isolation but proves the tree is complete.
sudo chroot rootfs /bin/sh -c 'echo inside; ls /'inside
bin
dev
etc
old_root
proc
sys
tmpIf this works, the filesystem is good, and the remaining steps are about isolation. Everything below runs from the directory that holds rootfs and the C source.
Step one: clone with namespace flags
The system call that creates a process in new namespaces is clone(2), which takes flags naming each namespace to create. glibc's wrapper takes a function to run and a stack for the child, because the child shares the parent's address space only if you ask for that, and the wrapper needs somewhere to run the function.
The skeleton below creates a child in six new namespaces and has it print its PID and hostname. The flags are CLONE_NEWNS for mounts, CLONE_NEWPID, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWNET and CLONE_NEWCGROUP. The low byte, SIGCHLD, tells the kernel to deliver that signal to the parent when the child exits, which is what makes waitpid work as usual.
#define _GNU_SOURCE
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#define STACK_SIZE (1024 * 1024)
static int child(void *arg)
{
(void)arg;
printf("child: pid=%d ppid=%d\n", getpid(), getppid());
return 0;
}
int main(void)
{
char *stack = malloc(STACK_SIZE);
if (!stack) { perror("malloc"); return 1; }
int flags = CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWUTS |
CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWCGROUP | SIGCHLD;
pid_t pid = clone(child, stack + STACK_SIZE, flags, NULL);
if (pid < 0) { perror("clone"); return 1; }
printf("parent: child is pid %d on the host\n", pid);
waitpid(pid, NULL, 0);
return 0;
}The stack argument is the top of the memory, because stacks grow downward on x86-64, and that is the classic mistake: passing stack instead of stack + STACK_SIZE gives a crash that looks unrelated. Compile and run it as root.
gcc -Wall -O2 step1.c -o step1
sudo ./step1parent: child is pid 48213 on the host
child: pid=1 ppid=0The child sees itself as PID 1 and its parent as 0, because its parent is outside its PID namespace and has no number there. The PID on the host line will differ on every run. The two lines may appear in the other order, since the processes run concurrently.
Creating namespaces needs CAP_SYS_ADMIN, so run as root. A later section covers the user-namespace route, which removes that requirement at the price of a different set of constraints.
Step two: let the parent finish the child's setup
Most of what a container needs cannot be done by the child alone. The cgroup must be created and the child's PID written into it by a process outside the container. The veth pair needs the child's PID so the host can move one end into its network namespace. And the child must not start the real workload until all of that exists.
The simplest synchronisation is a pipe. The parent creates it before clone, the child blocks reading from it, and the parent closes its write end when setup is finished. A read on a pipe whose writers have all closed returns 0, which unblocks the child.
int sync_pipe[2];
pipe(sync_pipe); /* before clone() */
/* in the child, before doing anything else: */
close(sync_pipe[1]);
char c;
read(sync_pipe[0], &c, 1); /* returns 0 once the parent closes its end */
close(sync_pipe[0]);
/* in the parent, after clone() and after setup is done: */
close(sync_pipe[1]);Both sides must close the end they do not use. If the child keeps the write end open, its own read never returns, because there is still a writer: itself.
Step three: the hostname
The UTS namespace holds the hostname, so the child can set it without touching the host. This is one line, and the first visible proof that isolation works.
if (sethostname("minic", 5) != 0) perror("sethostname");With the namespace in place, hostname in the container prints minic while the host's name is unchanged. Do it after the pipe read so a failure in the parent's setup does not leave a half-configured child running.
Step four: a private mount tree and a new root
This is the step where most hand-written runtimes go wrong, and the earlier posts on MS_PRIVATE and on chroot versus pivot_root explain the reasons. In outline:
A new mount namespace inherits shared mount propagation, so first make every mount private:
mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL).pivot_rootneeds the new root to be a mount point, so bind-mount the rootfs directory onto itself.Mount
procinside the new root so process tools work, plus a small/dev.Call
pivot_root(new_root, put_old)withput_oldinsidenew_root.chdir("/"), then unmount the old root withMNT_DETACHand remove its directory.
The /proc mount deserves a note. It must be mounted after the child is inside the new PID namespace, which clone guarantees, and it must be mounted in the new mount namespace, which is why it happens after the MS_PRIVATE call. A proc mounted this way shows only processes in the container's PID namespace, which is what makes ps inside correct.
For /dev, a runtime normally creates a fresh tmpfs and populates it with device nodes. The simplest safe approach for a teaching runtime is to mount a tmpfs at rootfs/dev and bind-mount a handful of host device files into it: null, zero, urandom, random and tty. Bind mounts of device files keep their meaning, and the container cannot create new nodes in a tmpfs mounted nodev.
static int bind_dev(const char *rootfs, const char *name)
{
char src[64], dst[256];
snprintf(src, sizeof src, "/dev/%s", name);
snprintf(dst, sizeof dst, "%s/dev/%s", rootfs, name);
int fd = open(dst, O_CREAT | O_WRONLY, 0666); /* create the target file */
if (fd >= 0) close(fd);
return mount(src, dst, NULL, MS_BIND, NULL);
}Call it for each of the five names after mounting the tmpfs and before pivot_root, because the source /dev is the host's and disappears from view afterwards.
Step five: cgroup v2 limits
The cgroup work is done by the parent, because it needs the child's host PID and because the child, after pivot_root, can no longer see /sys/fs/cgroup on the host anyway. The parent makes a directory, writes three limit files and moves the child in.
static int write_file(const char *path, const char *value)
{
int fd = open(path, O_WRONLY);
if (fd < 0) return -1;
ssize_t n = write(fd, value, strlen(value));
close(fd);
return n < 0 ? -1 : 0;
}
static int setup_cgroup(pid_t pid, char *path, size_t pathlen)
{
char file[300], buf[32];
snprintf(path, pathlen, "/sys/fs/cgroup/minic-%d", (int)pid);
if (mkdir(path, 0755) != 0) return -1;
snprintf(file, sizeof file, "%s/memory.max", path);
if (write_file(file, "67108864") != 0) return -1; /* 64 MiB */
snprintf(file, sizeof file, "%s/pids.max", path);
if (write_file(file, "64") != 0) return -1;
snprintf(file, sizeof file, "%s/cpu.max", path);
if (write_file(file, "50000 100000") != 0) return -1; /* half a CPU */
snprintf(file, sizeof file, "%s/cgroup.procs", path);
snprintf(buf, sizeof buf, "%d", (int)pid);
return write_file(file, buf);
}These files exist only if the parent group has the controllers enabled for its children. Check once before running the program.
cat /sys/fs/cgroup/cgroup.subtree_controlcpuset cpu io memory hugetlb pids rdma miscIf memory, cpu or pids is missing, enable it with echo "+memory +cpu +pids" | sudo tee /sys/fs/cgroup/cgroup.subtree_control. On a systemd host the common controllers are usually already on at the root. The memory.max of 64 MiB, pids.max of 64 and a half-CPU quota are values chosen to be easy to hit in tests; the earlier posts on limiting memory and CPU explain each file.
After the container exits, remove the directory with rmdir. A cgroup with live processes cannot be removed, so do it after waitpid returns.
The child's PID in the cgroup file is its host PID, which is what the parent has from clone's return value. Moving the child in before it executes anything is the reason for the pipe from step two: a process that has already forked children before it joins the group leaves those children behind.
Step six: networking
A new network namespace has only a down loopback interface. For the container to talk to anything, the parent creates a veth pair, moves one end into the child's namespace and configures both ends. The post on veth pairs walks through the commands one at a time, and the parent can run the same commands with system(3) after clone and before releasing the pipe.
static int setup_network(pid_t pid)
{
char cmd[512];
const char *steps[] = {
"ip link add minic-h type veth peer name minic-c",
"ip link set minic-c netns %d",
"ip addr add 10.200.0.1/24 dev minic-h",
"ip link set minic-h up",
"nsenter --target %d --net ip addr add 10.200.0.2/24 dev minic-c",
"nsenter --target %d --net ip link set minic-c up",
"nsenter --target %d --net ip link set lo up",
"nsenter --target %d --net ip route add default via 10.200.0.1",
};
for (size_t i = 0; i < sizeof steps / sizeof steps[0]; i++) {
snprintf(cmd, sizeof cmd, steps[i], (int)pid);
if (system(cmd) != 0) return -1;
}
return 0;
}The format strings that contain no %d are passed to snprintf with an extra argument, which is harmless. nsenter --net uses the child's network namespace through /proc/PID/ns/net, so the host's own ip binary configures the container's interface without needing any tools inside the rootfs. For internet access, add forwarding and a masquerade rule on the host once, as in the veth post. Deleting one end of the pair, or letting the namespace die with the container, removes the other end, so no cleanup is needed beyond that.
Use fixed interface names here, which limits the program to one container at a time. A real runtime generates unique names from the container ID.
Step seven: restrict what the process can do
At this point the process is isolated and limited, but it is still root with the full capability set of its namespaces, and it can call anything the kernel offers. Three small calls narrow that, and they go last in the child, after the mounts and before the execve.
Drop capabilities. The default capability set for root is large, and most of it is unneeded in a container. Drop CAP_SYS_ADMIN, CAP_SYS_MODULE, CAP_SYS_TIME, CAP_SYS_BOOT, CAP_MKNOD and others from the bounding set with prctl(PR_CAPBSET_DROP, cap). A loop over every capability number you do not want is the compact way.
Set no_new_privs. prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) stops the process and its descendants from gaining privileges through execve of a setuid binary or one with file capabilities. It is also required for loading a seccomp filter without privilege.
Load a seccomp filter. The post on adding a seccomp filter to a container runtime has the denylist, and the program below includes a shorter version of it. It rejects the calls that change the machine: module loading, reboot, mount, pivot_root, unshare, setns and a few more.
static int drop_privileges(void)
{
for (int cap = 0; cap <= CAP_LAST_CAP; cap++) {
if (cap == CAP_CHOWN || cap == CAP_DAC_OVERRIDE || cap == CAP_FOWNER ||
cap == CAP_KILL || cap == CAP_SETUID || cap == CAP_SETGID ||
cap == CAP_NET_BIND_SERVICE || cap == CAP_NET_RAW)
continue; /* keep a small useful set */
prctl(PR_CAPBSET_DROP, cap, 0, 0, 0);
}
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) return -1;
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
if (!ctx) return -1;
int deny[] = {
SCMP_SYS(init_module), SCMP_SYS(finit_module), SCMP_SYS(delete_module),
SCMP_SYS(reboot), SCMP_SYS(kexec_load), SCMP_SYS(swapon), SCMP_SYS(swapoff),
SCMP_SYS(mount), SCMP_SYS(umount2), SCMP_SYS(pivot_root),
SCMP_SYS(unshare), SCMP_SYS(setns), SCMP_SYS(settimeofday),
SCMP_SYS(clock_settime),
};
for (size_t i = 0; i < sizeof deny / sizeof deny[0]; i++)
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), deny[i], 0);
int rc = seccomp_load(ctx);
seccomp_release(ctx);
return rc;
}CAP_LAST_CAP comes from <linux/capability.h>, and on a kernel newer than your headers, capabilities above it stay in the set, so read /proc/sys/kernel/cap_last_cap if you want to be thorough. Dropping from the bounding set does not remove capabilities the process already has in its effective and permitted sets, which for root inside a fresh exec are recomputed from the bounding set at execve, so the drop takes effect when the container's command starts.
The complete program
Here is everything together. It takes the rootfs path and a command, and it cleans up its cgroup on exit.
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/capability.h>
#include <sched.h>
#include <seccomp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#define STACK_SIZE (1024 * 1024)
struct cfg {
const char *rootfs;
char *const *argv;
int pipefd[2];
};
static int write_file(const char *path, const char *value)
{
int fd = open(path, O_WRONLY);
if (fd < 0) return -1;
ssize_t n = write(fd, value, strlen(value));
close(fd);
return n < 0 ? -1 : 0;
}
static int pivot_root(const char *new_root, const char *put_old)
{
return syscall(SYS_pivot_root, new_root, put_old);
}
static int bind_dev(const char *rootfs, const char *name)
{
char src[64], dst[256];
snprintf(src, sizeof src, "/dev/%s", name);
snprintf(dst, sizeof dst, "%s/dev/%s", rootfs, name);
int fd = open(dst, O_CREAT | O_WRONLY, 0666);
if (fd >= 0) close(fd);
return mount(src, dst, NULL, MS_BIND, NULL);
}
static int drop_privileges(void)
{
for (int cap = 0; cap <= CAP_LAST_CAP; cap++) {
if (cap == CAP_CHOWN || cap == CAP_DAC_OVERRIDE || cap == CAP_FOWNER ||
cap == CAP_KILL || cap == CAP_SETUID || cap == CAP_SETGID ||
cap == CAP_NET_BIND_SERVICE || cap == CAP_NET_RAW)
continue;
prctl(PR_CAPBSET_DROP, cap, 0, 0, 0);
}
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) return -1;
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
if (!ctx) return -1;
int deny[] = {
SCMP_SYS(init_module), SCMP_SYS(finit_module), SCMP_SYS(delete_module),
SCMP_SYS(reboot), SCMP_SYS(kexec_load), SCMP_SYS(swapon), SCMP_SYS(swapoff),
SCMP_SYS(mount), SCMP_SYS(umount2), SCMP_SYS(pivot_root),
SCMP_SYS(unshare), SCMP_SYS(setns), SCMP_SYS(settimeofday),
SCMP_SYS(clock_settime),
};
for (size_t i = 0; i < sizeof deny / sizeof deny[0]; i++)
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), deny[i], 0);
int rc = seccomp_load(ctx);
seccomp_release(ctx);
return rc;
}
static int child(void *arg)
{
struct cfg *c = arg;
char path[256];
char tmp;
close(c->pipefd[1]);
if (read(c->pipefd[0], &tmp, 1) < 0) return 1; /* wait for the parent */
close(c->pipefd[0]);
if (sethostname("minic", 5) != 0) { perror("sethostname"); return 1; }
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) != 0) {
perror("make private"); return 1;
}
if (mount(c->rootfs, c->rootfs, NULL, MS_BIND | MS_REC, NULL) != 0) {
perror("bind rootfs"); return 1;
}
snprintf(path, sizeof path, "%s/proc", c->rootfs);
if (mount("proc", path, "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL) != 0) {
perror("mount proc"); return 1;
}
snprintf(path, sizeof path, "%s/dev", c->rootfs);
if (mount("tmpfs", path, "tmpfs", MS_NOSUID | MS_NOEXEC, "mode=755,size=1m") != 0) {
perror("mount dev"); return 1;
}
const char *devs[] = { "null", "zero", "urandom", "random", "tty" };
for (size_t i = 0; i < sizeof devs / sizeof devs[0]; i++)
if (bind_dev(c->rootfs, devs[i]) != 0) perror(devs[i]);
snprintf(path, sizeof path, "%s/old_root", c->rootfs);
if (pivot_root(c->rootfs, path) != 0) { perror("pivot_root"); return 1; }
if (chdir("/") != 0) { perror("chdir"); return 1; }
if (umount2("/old_root", MNT_DETACH) != 0) { perror("umount old root"); return 1; }
rmdir("/old_root");
if (drop_privileges() != 0) { perror("drop privileges"); return 1; }
clearenv();
setenv("PATH", "/bin", 1);
setenv("HOME", "/", 1);
execvp(c->argv[0], c->argv);
perror("execvp");
return 127;
}
static int setup_cgroup(pid_t pid, char *path, size_t pathlen)
{
char file[300], buf[32];
snprintf(path, pathlen, "/sys/fs/cgroup/minic-%d", (int)pid);
if (mkdir(path, 0755) != 0) return -1;
snprintf(file, sizeof file, "%s/memory.max", path);
if (write_file(file, "67108864") != 0) return -1;
snprintf(file, sizeof file, "%s/pids.max", path);
if (write_file(file, "64") != 0) return -1;
snprintf(file, sizeof file, "%s/cpu.max", path);
if (write_file(file, "50000 100000") != 0) return -1;
snprintf(file, sizeof file, "%s/cgroup.procs", path);
snprintf(buf, sizeof buf, "%d", (int)pid);
return write_file(file, buf);
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "usage: %s ROOTFS COMMAND [ARGS...]\n", argv[0]);
return 2;
}
struct cfg c = { .rootfs = argv[1], .argv = &argv[2] };
if (pipe(c.pipefd) != 0) { perror("pipe"); return 1; }
char *stack = malloc(STACK_SIZE);
if (!stack) { perror("malloc"); return 1; }
int flags = CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWUTS | CLONE_NEWIPC |
CLONE_NEWNET | CLONE_NEWCGROUP | SIGCHLD;
pid_t pid = clone(child, stack + STACK_SIZE, flags, &c);
if (pid < 0) { perror("clone"); return 1; }
char cg[128];
if (setup_cgroup(pid, cg, sizeof cg) != 0) perror("cgroup setup");
close(c.pipefd[0]);
close(c.pipefd[1]); /* releases the child */
int status = 0;
waitpid(pid, &status, 0);
rmdir(cg);
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}The program omits the network setup from step six, to keep it short. Add a call to setup_network(pid) right after setup_cgroup and before closing the pipe if you want the veth link; the function is above. Build and run it.
gcc -Wall -O2 minic.c -o minic -lseccomp
sudo ./minic ./rootfs /bin/sh -c 'hostname; id -u; ps; ls /'minic
0
PID USER TIME COMMAND
1 root 0:00 /bin/sh -c hostname; id -u; ps; ls /
2 root 0:00 ps
bin
dev
etc
proc
sys
tmpFour facts from that output prove the isolation. The hostname is minic, the UTS namespace at work. The shell is PID 1 and ps is PID 2, the PID namespace at work, with a fresh /proc showing only the container. The root listing is the rootfs directory, with old_root gone, so pivot_root and the detach worked. And the user is root, which is the thing a user namespace would change. The PID numbers for later commands may differ, because BusyBox sometimes runs applets in the shell's own process and sometimes forks.
Testing each limit
An isolation feature you have not tried to break is a feature you have not tested. Run these from inside the container, one at a time.
sudo ./minic ./rootfs /bin/sh -c 'mount -t tmpfs none /tmp; echo status=$?'mount: permission denied (are you root?)
status=1The mount is blocked by the seccomp filter, since the call returns EPERM. BusyBox's message wording differs from util-linux's.
sudo ./minic ./rootfs /bin/sh -c 'i=0; while [ $i -lt 100 ]; do sleep 100 & i=$((i+1)); done; echo spawned'sh: can't fork: Resource temporarily unavailable
sh: can't fork: Resource temporarily unavailable
spawnedWith pids.max at 64, the shell can start only about sixty background sleeps, and the rest fail with EAGAIN. The exact count of failures depends on how many processes the container already has. This is the fork bomb protection that the pids controller provides, and it is the reason a runtime sets it. For memory, run a program that allocates and touches more than 64 MiB, such as the hog from the cgroup post, copied into the rootfs, and it dies with Killed. For the CPU quota, run while :; do :; done & and watch top on the host.
Network isolation is easy to show: ip link inside the container with no setup_network call shows only a down lo, while the host's interfaces are invisible.
The init problem: PID 1 duties
The command you run becomes PID 1 of its namespace, and the kernel treats PID 1 specially. Signals for which it has installed no handler are ignored for PID 1 when sent from within the namespace, so kill -TERM 1 from inside does nothing unless the process handles it. And PID 1 is responsible for reaping orphaned children: when a process's parent dies, the kernel reparents it to the namespace's PID 1, and if PID 1 never calls wait, the zombies accumulate.
A shell as PID 1, as in the examples, copes for short sessions. A real workload does not always. If you run an application that spawns children and does not reap them, you need a tiny init. Two ways exist. Make your runtime fork once more: the PID 1 process becomes a small reaper that runs the real command as its child, forwards signals to it and calls waitpid(-1) in a loop, and exits with the child's status. Or ship a purpose-built init such as tini in the image, as Docker's --init option does. The reaper loop is a few lines.
for (;;) {
int st;
pid_t w = waitpid(-1, &st, 0);
if (w == worker) return WIFEXITED(st) ? WEXITSTATUS(st) : 128 + WTERMSIG(st);
if (w < 0 && errno == ECHILD) return 0;
}Signal forwarding is the other half: install handlers for SIGTERM and SIGINT in the init that call kill(worker, sig), so that docker stop-style termination reaches the application.
Rootless: the user namespace route
The runtime above must run as root, because creating most namespaces and writing to the cgroup tree require privilege. A user namespace removes the first requirement. Add CLONE_NEWUSER to the flags, and the child starts with a full capability set inside its own user namespace, which owns the new namespaces created with it. Before the child does anything, the parent must write the ID mapping, or the child's UID shows as the overflow ID 65534 and file access fails.
static int write_map(pid_t pid, const char *which, const char *line)
{
char path[64];
snprintf(path, sizeof path, "/proc/%d/%s", (int)pid, which);
return write_file(path, line);
}
/* in the parent, after clone(), for the calling user with uid 1000 */
write_map(pid, "setgroups", "deny");
write_map(pid, "uid_map", "0 1000 1");
write_map(pid, "gid_map", "0 1000 1");The mapping line means "UID 0 inside maps to UID 1000 outside, for a range of 1 ID". Writing deny to setgroups first is required for an unprivileged writer of gid_map. The post on uid_map and gid_map in this series covers the rules and the multi-ID mappings that newuidmap provides.
Rootless mode changes more than the flags. mount of proc needs a PID namespace you own and, on recent kernels, a fully visible /proc in the parent. Binding device files needs the right access to the host's files. The veth setup needs privilege on the host, so rootless runtimes use user-space networking such as slirp4netns or pasta instead. Cgroup writes need a delegated subtree from systemd, where the unit has Delegate=yes. Each of these is a place where the root-only program above takes a shortcut that the rootless one cannot.
What this program does not do
The runtime is honest about its goal, which is understanding, not safety. These are the gaps you must close before you run anything you do not trust.
No image handling. A real runtime takes an image, a stack of layers, and unpacks it into a root filesystem, usually with an overlay filesystem so the base layers stay read-only and shared. Here the rootfs is a directory you built, and writes go straight into it.
No path safety. The runtime opens files by path under a directory the container controls, such as creating device nodes in rootfs/dev. A hostile rootfs can place symbolic links that redirect these operations to the host. runc and other runtimes defend with openat2 flags, checks of the resolved path, and helper libraries such as filepath-securejoin.
No masking of kernel interfaces. Paths like /proc/kcore, /proc/sys, /sys/firmware and /proc/sysrq-trigger expose or alter host state, and runtimes mask or mount them read-only. Our container mounts a full /proc with default access.
A weak syscall filter. A denylist fails open. A production profile is an allowlist, with architecture checks, and argument filters on calls like clone that can create namespaces.
No handling of leaked file descriptors. Any descriptor the parent leaves open at clone time is inherited by the child, and a descriptor that refers to the host's filesystem can be used to escape. runc closes everything above a threshold and opens its own files with O_CLOEXEC. The program above opens only a few files and closes them, but it passes no sensitive descriptors on purpose, not by checking.
No resource accounting for the runtime itself, no logging, no exec into a running container and no lifecycle states. Docker's docker exec is a setns into each namespace and a cgroup join, and a runc state file is a JSON file the runtime keeps.
How runc relates to this
If you read runc's source after writing this program, the structure will be familiar and the differences instructive. Its create step does what the child does here, up to blocking on a pipe or FIFO, and its start step releases it, which is the same pause point the pipe provides, extended to a state machine that outlives the process. It builds a config from the OCI bundle's JSON, as the post on the OCI runtime spec shows, instead of from hard-coded values. It does its namespace setup in C code that runs before the Go runtime starts, because setns into a PID or user namespace needs a single-threaded process. And it layers the safety checks above on every file operation.
The Docker and runc post in this series shows the layers above runc: containerd, the shim and the daemon. Nothing in them changes the kernel mechanisms you have just used.
Troubleshooting
When something fails, the error names the system call, so start there.
| Symptom | Likely cause |
|---|---|
clone: Operation not permitted | Not root, or a seccomp or AppArmor profile blocks namespace creation |
make private: Invalid argument | The mount namespace was not created, or / is not a mount point in it |
pivot_root: Invalid argument | new_root is not a mount point, put_old is not under it, or propagation is still shared |
pivot_root: Device or resource busy | put_old is on the same mount as new_root, or the rootfs is on a ramfs |
mount proc: Operation not permitted | The PID namespace is missing, or /proc has locked mounts from an outer container |
execvp: No such file or directory | The binary is missing in the rootfs, or is dynamically linked without its libraries and loader |
| Container hangs at start | The parent never closed the pipe, or the child kept its write end open |
cgroup setup: No such file or directory | A controller is not enabled in the parent's subtree_control |
Killed with no message | The memory limit was hit and the OOM killer ran, as memory.events records |
Run the container under strace -f on the host to see each call and its error code. The mount-related failures are the most common, and findmnt inside the namespace, with /proc/self/mountinfo as the source of truth, shows what the tree looks like at the moment of failure.
Where to go from here
Each of the pieces in this guide has its own post in this series. The namespaces post covers all eight types, and the unshare and nsenter post lets you try them from a shell. The cgroup posts explain the files, the hierarchy rule and the v1 differences. The mount posts go deep on propagation and pivot_root. The veth and seccomp posts cover networking and filtering, and the OCI post shows the standard configuration format. For stronger isolation than a container can give, the later posts on microVMs and Firecracker show the other end of the spectrum, where the same ideas, a restricted process with limited access to the host, are enforced by hardware virtualization instead of by the kernel's own software boundaries.
The life of one container, in order
It helps to hold the whole sequence in your head before changing any part of it. The parent allocates a stack and a pipe, then calls clone with the namespace flags. From that instant the child exists in its own PID, mount, UTS, IPC, network and cgroup namespaces, but it shares nothing it has not been given, and it is blocked on the pipe. The parent, still in the host's namespaces, creates a cgroup named after the child's host PID, writes the limits, and writes the PID into cgroup.procs. Optionally it builds the veth pair. Only then does it close the pipe.
The child wakes, sets its hostname, cuts the propagation link with MS_PRIVATE, bind-mounts the rootfs onto itself, mounts proc and a small /dev, and pivots. After the pivot it detaches the old root, which is the moment the container loses any path back to the host's files. It then drops capabilities, sets no_new_privs, loads the seccomp filter, cleans the environment and calls execvp. When the program exits, the parent's waitpid returns, the cgroup is empty and can be removed, and the namespaces vanish with their last member, taking the mounts, the network interface and the hostname with them. Nothing needs undoing on the host except the cgroup directory, which is why container teardown is cheap.
Notice what the parent never does: it never enters the container's filesystem or runs code in its namespaces, except through nsenter for network setup. The parent can stay privileged and trusted, and the child can be as restricted as you like, because the line between them is a clean process boundary. Production runtimes keep that structure, and add one more process, the shim, so the runtime can exit while the container keeps running.
Reading what the kernel recorded
After a run, the cgroup has already been removed, so to inspect it you need a container that is still running. Start one that sleeps, and look at its files from another terminal. The PID in the directory name is the child's host PID, which you can read from ps or from the cgroup directory name itself.
sudo ./minic ./rootfs /bin/sleep 60 &
sleep 1
ls -d /sys/fs/cgroup/minic-*
cat /sys/fs/cgroup/minic-*/pids.current
cat /sys/fs/cgroup/minic-*/memory.current
cat /sys/fs/cgroup/minic-*/cpu.stat | head -n 3/sys/fs/cgroup/minic-48213
1
110592
usage_usec 2144
user_usec 1032
system_usec 1112The group has one process, uses about a hundred kilobytes of memory, and has consumed a couple of milliseconds of CPU. The numbers will differ on your machine. memory.events counts how often the memory limit was reached and memory.peak records the high-water mark. When a container is killed for exceeding its memory, memory.events shows oom_kill 1, which is the first place to look when an application dies with no message of its own.
The namespace side is equally visible. The container's PID on the host gives you its namespace files, and lsns lists them with their owners.
sudo lsns -p "$(pgrep -f 'sleep 60' | head -n 1)" NS TYPE NPROCS PID USER COMMAND
4026531837 user 312 1 root /sbin/init
4026532611 mnt 1 48214 root /bin/sleep 60
4026532612 uts 1 48214 root /bin/sleep 60
4026532613 ipc 1 48214 root /bin/sleep 60
4026532614 pid 1 48214 root /bin/sleep 60
4026532615 net 1 48214 root /bin/sleep 60
4026532616 cgroup 1 48214 root /bin/sleep 60Six namespaces hold exactly one process, the container's, and the user namespace is the host's, shared with 312 other processes, because this runtime does not create one. The PIDs and inode numbers will differ. That one line, a user namespace that is not new, is the most important fact about the root-only version of this program: root inside the container is root on the host, held back only by the capability drop, the seccomp filter and the filesystem boundary.
Layers: giving containers a writable view without copying
The rootfs in this guide is one directory, and the container writes into it. That is fine for an experiment and wrong for a platform, where hundreds of containers start from one image and must not see or change each other's files. The kernel's answer is the overlay filesystem. It stacks a read-only lower directory under a writable upper one and presents the merged view. Reads fall through to the lower layer, and writes go to the upper one, copying a file up on first modification.
mkdir -p base upper work merged
sudo mount -t overlay overlay \
-o lowerdir=rootfs,upperdir=upper,workdir=work merged
echo changed | sudo tee merged/etc/motd
ls rootfs/etc upper/etcpasswd
motdThe base rootfs/etc still has only passwd, while the new motd file exists in upper/etc. Pass merged to the runtime instead of rootfs and every container gets a private writable layer over a shared base, which is exactly what image layers are in Docker's overlay2 storage driver. Several lower directories can be stacked, separated by colons in lowerdir, with the leftmost on top, so an image of many layers is a long lowerdir list. Mount the overlay in the parent before clone, or inside the child's mount namespace after making propagation private, and remove the upper directory when the container is deleted.
Overlay mounts inside a user namespace need kernel support for unprivileged overlay mounts, available since Linux 5.11, and the userxattr option for the metadata they use. A rootless runtime either uses that or falls back to a user-space implementation such as fuse-overlayfs.
Entering a running container
docker exec is not magic. It is a new process that joins the namespaces of a running container and is moved into its cgroup, which is a few calls: open each file under /proc/PID/ns, call setns on it, then fork the command. A process that joins a PID namespace with setns does not move itself into it, but its children do, so the fork matters.
#define _GNU_SOURCE
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char **argv)
{
if (argc < 3) { fprintf(stderr, "usage: %s PID COMMAND...\n", argv[0]); return 2; }
const char *ns[] = { "user", "mnt", "uts", "ipc", "net", "pid", "cgroup" };
for (size_t i = 0; i < sizeof ns / sizeof ns[0]; i++) {
char path[64];
snprintf(path, sizeof path, "/proc/%s/ns/%s", argv[1], ns[i]);
int fd = open(path, O_RDONLY);
if (fd < 0) { perror(path); return 1; }
if (setns(fd, 0) != 0) { perror("setns"); return 1; }
close(fd);
}
pid_t child = fork();
if (child == 0) {
chdir("/");
execvp(argv[2], &argv[2]);
perror("execvp");
_exit(127);
}
int status;
waitpid(child, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
}Run it as sudo ./exec PID /bin/sh against the container's host PID. The order of the setns calls matters: join the user namespace first, if there is one, because the others need the capabilities it grants, and the mount namespace before the commands that open files by path. This simplified version does not move the new process into the container's cgroup or apply the container's capability and seccomp restrictions, so a command entered this way is less constrained than the original. runc exec applies the same restrictions to the new process, and that is why using the runtime's own exec is the safe way into a production container.
Choosing limits that mean something
The values in the program are chosen to be easy to trip, not to be right. For a real workload, set each limit from observation. Run the application with generous limits, read memory.peak and cpu.stat after a representative load, and set memory.max at the peak plus headroom. A limit tighter than the working set turns every spike into an OOM kill, and a limit with no headroom means that the page cache, which the group is charged for, competes with the application's own memory. If you want slowing instead of killing, set memory.high below memory.max and let the kernel throttle at the soft limit.
For CPU, cpu.max caps the group in absolute terms and cpu.weight only divides contested time. A quota creates throttling that shows up as latency spikes in bursty workloads, because a process that spends its quota early in the 100 millisecond period waits for the next one, so prefer weights for shared hosts and quotas for strict isolation. pids.max should be high enough for the application's real thread and process count, which pids.peak reports, and low enough to stop a fork bomb.
Where the isolation stops
This is the most useful section to read before running anything that matters. Every container on a host runs against one kernel, so a kernel vulnerability reachable through a permitted system call is a way out of every container at once. The seccomp filter, the dropped capabilities and the masked kernel paths reduce what is reachable, but they do not remove the kernel as a shared component. Some resources are not namespaced at all: the system clock, the kernel keyring in some configurations, the module list, and the kernel's own memory. Side channels in the CPU do not respect any of these boundaries.
The practical rules are the ones platforms follow. Run workloads you do not control with a user namespace, an allowlist seccomp profile, no extra capabilities and a read-only root. Keep the host kernel patched. And when the workload is truly hostile and the cost of a breakout is high, add a hardware boundary: run each container inside a lightweight virtual machine, as the Firecracker posts in this series describe.


