← Back to Home

📦 Containers from Scratch

A working container runtime in about 90 lines of Python, without root: namespaces, an overlayfs image, pivot_root, and cgroup limits that really kill, block and throttle.

A container isn't a small virtual machine. There's no hypervisor and no guest kernel. A container is an ordinary Linux process that the kernel shows a restricted view of the system: its own process list, its own filesystem, its own hostname and network, and limits on how much CPU, memory and how many processes it may use. Docker, Podman, containerd and Kubernetes are layers of tooling around a handful of kernel features.

The best way to see that is to build one. This article writes a working container runtime in about 90 lines of Python, without root, and uses it to test each mechanism: namespaces, an overlay root filesystem, pivot_root, and cgroup limits that really kill, block and throttle. It ran on Linux 6.18 (WSL2) with Python 3.12, using a 2 MB busybox image.

It builds on Operating System Essentials, which covered processes, system calls and virtual memory, and Kubernetes Internals, which sits on top of everything here.

A Container Is a Process

Start a container running sleep, then look at it from the host (the user name is changed to dev):

host sees the container's PID 1 as PID 76509:
    PID    PPID USER     COMMAND
  76509   76508 dev      /bin/sleep 3
namespaces (container vs this shell):
  user   user:[4026532288]      user:[4026531837]
  pid    pid:[4026532292]       pid:[4026532213]
  mnt    mnt:[4026532289]       mnt:[4026532211]
  uts    uts:[4026532290]       uts:[4026532212]
  net    net:[4026532293]       net:[4026531833]
  ipc    ipc:[4026532291]       ipc:[4026532199]
  cgroup cgroup:[4026532210]    cgroup:[4026532210]
uid_map:          0       1000          1
cgroup: 0::/user.slice/user-1000.slice/user@1000.service/app.slice/run-re0370e2b3d424432b623ddcdc35b8a7f.scope/box2

The host's ps shows an ordinary process with an ordinary PID, owned by an ordinary user. What makes it a container is in /proc/<pid>/ns/: links to the namespaces it belongs to. Six of them differ from the host shell's. The uid_map says user 0 (root) inside is user 1000 outside. And it lives in its own cgroup, where limits are applied.

The Building Blocks

Mechanism Isolates or limits Without it
PID namespace Process IDs: the container sees only its own processes, and its first process is PID 1 It sees and can signal every process on the host
Mount namespace The list of mounted filesystems Its mounts would appear on the host, and vice versa
Root filesystem (pivot_root, overlayfs) What / is It sees the host's files
UTS namespace Hostname and domain name Changing the hostname changes the host's
Network namespace Interfaces, routes, firewall rules, ports It shares the host's network and port numbers
IPC namespace System V IPC and POSIX message queues Shared memory segments are shared with the host
User namespace User and group IDs: root inside maps to an unprivileged user outside Root in the container is root on the host
cgroup namespace Its view of the cgroup tree It sees the host's cgroup paths (tinybox doesn't create one, as the output above shows)
Time namespace Boot and monotonic clock offsets Rarely needed
cgroups v2 How much CPU, memory, I/O and how many processes One container can starve the whole machine
Capabilities, seccomp, LSMs Which privileged operations and system calls are allowed A root process can do anything the kernel allows root to do

Namespaces control what a process can see; cgroups control how much it can use; capabilities, seccomp and AppArmor or SELinux control what it may do. A container runtime is the code that sets all of these up before running your program.

Build One, Piece by Piece

Switch each mechanism on and see what a shell inside can see and do. Outputs inside the container are the ones tinybox produced below; host values are illustrative:

isolatedshared with the hostalways shared

The last row never changes: every container shares the host's kernel. That's what makes containers light (no second operating system to boot) and also what limits their isolation, covered at the end.

The Runtime: tinybox

Here's the whole runtime. It takes an image directory and a command, and runs the command in a container with optional memory, process and CPU limits:

"""tinybox: a container runtime in ~120 lines of Python. Linux only, no root needed (user namespaces).
Usage (inside a delegated cgroup, e.g. `systemd-run --user --scope -p Delegate=yes -p CPUAccounting=yes`):
    python3 tinybox.py --mem 64M --pids 20 --cpu 0.5 --name box1 IMAGE_DIR -- /bin/sh -c 'echo hi'"""
import argparse, ctypes, os, shutil, socket, sys

exit_code = lambda status: (lambda c: 128 - c if c < 0 else c)(os.waitstatus_to_exitcode(status))   # killed by signal N -> 128+N

libc = ctypes.CDLL("libc.so.6", use_errno=True)
MS_BIND, MS_REC, MS_PRIVATE, MNT_DETACH = 0x1000, 0x4000, 1 << 18, 2


def mount(src, target, fstype, flags=0, data=None):
    if libc.mount(src.encode(), target.encode(), fstype.encode() if fstype else None, flags, data.encode() if data else None) != 0:
        raise OSError(ctypes.get_errno(), f"mount {src} -> {target}: {os.strerror(ctypes.get_errno())}")


def pivot_root(new_root, put_old):
    if libc.syscall(155, new_root.encode(), put_old.encode()) != 0:           # 155 = SYS_pivot_root on x86-64
        raise OSError(ctypes.get_errno(), "pivot_root")


def setup_cgroup(name, mem, pids, cpu):
    """Create <our scope>/<name> with limits. We first move ourselves into a 'runtime' child so the scope
    has no processes of its own (cgroup v2's 'no internal processes' rule), then enable controllers."""
    rel = open("/proc/self/cgroup").read().strip().split("::")[1]
    base = f"/sys/fs/cgroup{rel}"
    os.makedirs(f"{base}/runtime", exist_ok=True)
    open(f"{base}/runtime/cgroup.procs", "w").write(str(os.getpid()))
    open(f"{base}/cgroup.subtree_control", "w").write("+memory +pids +cpu")
    cg = f"{base}/{name}"; os.makedirs(cg, exist_ok=True)
    if mem: open(f"{cg}/memory.max", "w").write(mem); open(f"{cg}/memory.swap.max", "w").write("0")
    if pids: open(f"{cg}/pids.max", "w").write(str(pids))
    if cpu: open(f"{cg}/cpu.max", "w").write(f"{int(cpu * 100000)} 100000")      # quota per 100 ms period
    return cg


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--mem"); ap.add_argument("--pids", type=int); ap.add_argument("--cpu", type=float)
    ap.add_argument("--name", default="box"); ap.add_argument("image"); ap.add_argument("cmd", nargs=argparse.REMAINDER)
    a = ap.parse_args(); cmd = a.cmd[1:] if a.cmd[:1] == ["--"] else a.cmd

    cg = setup_cgroup(a.name, a.mem, a.pids, a.cpu)
    state = os.path.abspath(f"state/{a.name}")                     # per-container writable layer
    for top, dirs, _ in os.walk(state):                            # overlayfs leaves work/work with mode 000:
        for d in dirs: os.chmod(os.path.join(top, d), 0o700)       # fix each one before os.walk descends into it
    shutil.rmtree(state, ignore_errors=True)
    for d in ("upper", "work", "merged"): os.makedirs(f"{state}/{d}")
    uid, gid = os.getuid(), os.getgid()
    r, w = os.pipe()

    pid = os.fork()
    if pid:                                                         # parent: put the child in the cgroup, then release it
        os.close(r)
        open(f"{cg}/cgroup.procs", "w").write(str(pid))
        os.write(w, b"go"); os.close(w)
        _, status = os.waitpid(pid, 0)
        code = exit_code(status)
        events = dict(l.split() for l in open(f"{cg}/memory.events"))
        cpu = dict(l.split() for l in open(f"{cg}/cpu.stat"))
        print(f"[tinybox] exit code {code} | oom_kill={events['oom_kill']} | cpu usage {int(cpu['usage_usec']) / 1e6:.2f} s, "
              f"throttled {cpu['nr_throttled']} of {cpu['nr_periods']} periods | upper layer now holds: {sorted(os.listdir(state + '/upper'))}", file=sys.stderr)
        sys.exit(code)

    os.close(w); os.read(r, 2)                                      # wait until we're in the cgroup
    # 1. New namespaces: user (become root inside), mount, hostname, IPC, network, PID
    os.unshare(os.CLONE_NEWUSER | os.CLONE_NEWNS | os.CLONE_NEWUTS | os.CLONE_NEWIPC | os.CLONE_NEWNET | os.CLONE_NEWPID)
    open("/proc/self/setgroups", "w").write("deny")
    open("/proc/self/uid_map", "w").write(f"0 {uid} 1")             # uid 0 inside = our uid outside
    open("/proc/self/gid_map", "w").write(f"0 {gid} 1")
    if os.fork():                                                    # the next child is PID 1 in the new PID namespace
        _, status = os.waitpid(-1, 0); os._exit(exit_code(status))

    socket.sethostname(a.name)
    mount("none", "/", None, MS_REC | MS_PRIVATE)                    # don't propagate our mounts to the host
    # 2. Root filesystem: read-only image + writable upper layer, merged by overlayfs
    merged = f"{state}/merged"
    mount("overlay", merged, "overlay", 0, f"lowerdir={os.path.abspath(a.image)},upperdir={state}/upper,workdir={state}/work")
    mount("proc", f"{merged}/proc", "proc")
    mount("tmpfs", f"{merged}/tmp", "tmpfs")
    for dev in ("null", "zero", "urandom"):
        open(f"{merged}/dev/{dev}", "a").close(); mount(f"/dev/{dev}", f"{merged}/dev/{dev}", None, MS_BIND)
    # 3. Swap the root: the image becomes /, the old root is detached and disappears
    os.makedirs(f"{merged}/.oldroot", exist_ok=True)
    pivot_root(merged, f"{merged}/.oldroot")
    os.chdir("/")
    libc.umount2(b"/.oldroot", MNT_DETACH); os.rmdir("/.oldroot")
    os.execvpe(cmd[0], cmd, {"PATH": "/bin", "HOME": "/root", "PS1": f"{a.name}# "})


if __name__ == "__main__":
    main()

The steps, in order:

  1. cgroup: create a child cgroup under the one we're running in, and write the limits into memory.max, pids.max and cpu.max. cgroup v2 has a "no internal processes" rule (a cgroup that hands controllers to its children can't contain processes itself), so the runtime first moves itself into a runtime child.
  2. fork: the child waits on a pipe until the parent has put it into the container's cgroup, so that everything it later starts is limited.
  3. unshare: create new user, mount, UTS, IPC, network and PID namespaces in one system call. Then write the uid/gid maps: user 0 inside is our own uid outside. A process may map its own uid in a user namespace it created, which is why no root is needed: within that namespace we hold all capabilities, but only over resources the namespace owns.
  4. fork again: a new PID namespace applies to the children of the process that created it, so the next child becomes PID 1.
  5. hostname, and mark all mounts private so that nothing mounted next leaks to the host.
  6. Root filesystem: overlay the read-only image with a per-container writable layer; mount a fresh /proc (which, inside a new PID namespace, shows only the container's processes), a tmpfs on /tmp, and bind-mount /dev/null, /dev/zero and /dev/urandom.
  7. pivot_root makes the merged directory the new / and puts the old root at /.oldroot; unmounting that removes the last path back to the host's files. (chroot would be simpler but leaves the old root mounted and reachable.)
  8. exec the command. From here on, it's just a program running in a strange-looking world.

It runs inside a systemd user scope with Delegate=yes, which hands a cgroup subtree to an unprivileged user. That's also how rootless Podman and Docker get cgroups:

#!/bin/sh
# Run tinybox inside a systemd user scope that delegates its cgroup subtree to us.
exec systemd-run --user --scope -q -p Delegate=yes -p CPUAccounting=yes -p MemoryAccounting=yes -p TasksAccounting=yes \
  python3 "$(dirname "$0")/tinybox.py" "$@"

And the image is a directory with a statically linked busybox and its 271 command symlinks, 2.1 MB in total:

mkdir -p image/bin image/proc image/tmp image/dev image/root image/etc
cp /usr/bin/busybox image/bin/
for a in $(/usr/bin/busybox --list); do [ -e image/bin/$a ] || ln -s busybox image/bin/$a; done
echo "root:x:0:0:root:/root:/bin/sh" > image/etc/passwd
echo "hello from the image" > image/etc/motd

Inside the Box

The first run, with a script that looks around and changes a few files:

hostname: box1
id: uid=0(root) gid=0 groups=65534,65534,65534,65534,65534,65534,65534,65534,65534,65534,65534,65534,0
pid of this shell: 1
PID   USER     COMMAND
    1 root     /bin/sh -c echo "hostname: $(hostname)"; echo "id: $(id)"; echo "pid of this shell: $$"; ps; echo "network interfaces:"; ls /sys/class/net 2>/dev/null || cat /proc/net/dev | tail -n +3 | cut -d: -f1; cat /etc/motd; echo hi > /etc/motd; touch /created-inside; ls /
    4 root     {ps} /bin/sh -c echo "hostname: $(hostname)"; echo "id: $(id)"; echo "pid of this shell: $$"; ps; echo "network interfaces:"; ls /sys/class/net 2>/dev/null || cat /proc/net/dev | tail -n +3 | cut -d: -f1; cat /etc/motd; echo hi > /etc/motd; touch /created-inside; ls /
network interfaces:
    lo
hello from the image
bin
created-inside
dev
etc
proc
root
tmp
[tinybox] exit code 0 | oom_kill=0 | cpu usage 0.01 s, throttled 0 of 1 periods | upper layer now holds: ['created-inside', 'dev', 'etc']
=== box2 does not see box1's changes:
bin
dev
etc
proc
root
tmp
hello from the image
[tinybox] exit code 0 | oom_kill=0 | cpu usage 0.01 s, throttled 0 of 0 periods | upper layer now holds: ['dev']

Images and Overlayfs

That separation comes from overlayfs, which merges a read-only lower directory and a writable upper directory into one view. It works without root inside a user namespace:

merged=changed lower=base
f
g

Writing f in the merged view copied it up into the upper directory and changed the copy; the lower file still says base. New file g exists only in the upper layer. Deleting a lower file creates a "whiteout" marker in the upper layer that hides it.

A container image is a stack of these layers. Each instruction in a Dockerfile that changes files produces a layer: a tar archive of the changed files. The runtime unpacks the layers and mounts them as overlay lowerdirs, with a fresh upper layer for each container. That's why:

The OCI image specification standardises this format (layer tarballs, a JSON config and a manifest), so images built by Docker, Buildah or kaniko run on any OCI runtime.

cgroups: Limits That Bite

Namespaces don't limit anything; a process in a namespace can still use all the memory and CPU on the machine. cgroups do. Three limits, each tested for real:

Memory. With memory.max = 64M (and no swap), a shell tries to hold 150 MB in a variable:

=== memory.max 64M: hold 150 MB in a shell variable
[tinybox] exit code 137 | oom_kill=1 | cpu usage 0.79 s, throttled 0 of 0 periods | upper layer now holds: ['dev']

The kernel's OOM killer killed it inside the cgroup, without touching anything else on the machine. Exit code 137 is 128 + 9: killed by SIGKILL. This is the OOMKilled status in Kubernetes, and the cgroup's memory.events file counts it (oom_kill=1). Without the limit, the same command succeeded and used 150 MB of host memory. There's also memory.high, a softer limit that throttles and reclaims memory before the hard limit kills.

Processes. With pids.max = 20, start 30 background sleeps:

=== pids.max 20: start 30 background sleeps
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 /bin/sh: can't fork: Resource temporarily unavailable

Eighteen sleeps, the shell and the runtime's PID-1 process make 20 tasks; the next fork failed with EAGAIN. This is what stops a fork bomb in one container from taking down the host.

CPU. With cpu.max = "50000 100000" (50 ms of CPU time per 100 ms period, half a CPU), run a busy loop for 3 seconds of wall time, then the same loop with no limit:

=== cpu.max 0.5 CPU: busy loop for 3 s of wall time
loop iterations: 5692
[tinybox] exit code 0 | oom_kill=0 | cpu usage 1.89 s, throttled 38 of 38 periods | upper layer now holds: ['dev']

=== same loop with no CPU limit
loop iterations: 10720
[tinybox] exit code 0 | oom_kill=0 | cpu usage 3.17 s, throttled 0 of 0 periods | upper layer now holds: ['dev']

53% of the work in the same wall time, and every 100 ms period was throttled: the process used up its 50 ms, then was stopped until the next period began.

That pause is the hidden cost of CPU limits. A request arriving at a throttled container waits for the next period, up to tens of milliseconds, even when the host's CPUs are idle. A multi-threaded program can use its whole quota in a fraction of the period and then stall. This is why many teams set Kubernetes CPU requests (which become relative cpu.weight, a share of CPU under contention) but leave CPU limits off for latency-sensitive services, while always setting memory limits. Watch nr_throttled in cpu.stat (or container_cpu_cfs_throttled_periods_total in Prometheus) if latency is mysteriously high.

What Real Runtimes Add

tinybox has the core of a container runtime. Production runtimes add:

A Kubernetes pod is a group of containers that share some namespaces (network and IPC, optionally PID) inside a common cgroup. A tiny "pause" container holds the shared namespaces open so that app containers can restart without losing the pod's IP address. Every container in a pod sees the same localhost, which is how sidecars work.

How Strong Is the Isolation?

Containers share the host kernel. Any kernel vulnerability reachable through the system calls a container can make is a potential escape, and so is any careless configuration: a privileged container, a mounted Docker socket, a sensitive host path bind-mounted inside. Practical rules:

Key Takeaways

Copied to clipboard!