Linux Containers by Hand. Part 2: Building an OCI bundle and running it with runc

All parts of the series “Linux Containers by Hand”

In Part 1 we installed containerd and ran a container with ctr run. We saw runc create the container and exit, and containerd supply the container specification. Today we will trace how containerd invokes runc and what it passes in, then build the same specification by hand and launch the container with one runc command. We will use containerd only to retrieve the image files.

The script that builds a container bundle from an image is in the linux-containers-by-hand repository.


Lab setup

Item Value
Machine lincont-lab.example.com, 192.168.10.31, Hyper-V VM with 4 vCPUs and 8 GB RAM
OS Ubuntu Server 26.04.1, kernel 7.0.0
containerd 2.4.2
runc 1.5.2, OCI specification 1.3.0
nerdctl 2.4.2
strace 6.19
Image docker.io/library/alpine:3.24

Install containerd, runc, and nerdctl as in Part 1, from GitHub releases, with containerd running as a systemd service. Ubuntu Server includes strace. Run all commands as root (sudo -i).

Here is the plan.

   Through containerd                  By hand
   ──────────────────                  ───────
   ctr                                 us
    │                                   │
    ▼                                   │
   containerd                           │  nerdctl export → rootfs
    │  bundle: config.json, rootfs      │  runc spec      → config.json
    ▼                                   │
   containerd-shim-runc-v2              │
    │                                   │
    ▼                                   ▼
   runc create, start, kill, delete    runc run, create, start, kill, delete
    │                                   │
    ▼                                   ▼
   container process                   container process

The left side shows the container’s path in Part 1. On the right, we prepare the bundle directory and invoke runc ourselves, without involving containerd or the shim in the launch.


How containerd invokes runc

Trace the launch

Let’s see what runs when ctr creates a container. strace prints a process’s system calls, the requests it makes to the kernel. -p attaches to a running process, -f follows its descendants, and -e trace=execve selects the execve call that executes a program. Give strace a second to attach before starting the container.

img=docker.io/library/alpine:3.24
ctr image pull $img > /dev/null
strace -f -qq -s 300 -e trace=execve -e signal=none -o /tmp/exec.trace -p $(pidof containerd) &
sleep 1
ctr run -d $img sleeper sleep 100000

The trace records each call with its process ID and argument array. Keep only the shim and runc launches and format their arguments as command lines.

grep -E 'execve\("[^"]*(runc|shim)' /tmp/exec.trace | sed -E 's/^([0-9]+) +execve\("[^"]*", \[(.*)\], 0x.*/\1 \2/; s/", "/ /g; s/"//g'
ps -o pid,ppid,cmd --forest -C containerd-shim-runc-v2,sleep
5867 /usr/local/bin/containerd-shim-runc-v2 -namespace default -address /run/containerd/containerd.sock -publish-binary /usr/local/bin/containerd -id sleeper start
5876 /usr/local/bin/containerd-shim-runc-v2 -namespace default -id sleeper -address /run/containerd/containerd.sock
5886 runc --root /run/containerd/runc/default --log /run/containerd/io.containerd.runtime.v2.task/default/sleeper/log.json --log-format json create --bundle /run/containerd/io.containerd.runtime.v2.task/default/sleeper --pid-file /run/containerd/io.containerd.runtime.v2.task/default/sleeper/init.pid sleeper
5907 runc --root /run/containerd/runc/default --log /run/containerd/io.containerd.runtime.v2.task/default/sleeper/log.json --log-format json start sleeper
    PID    PPID CMD
   5876       1 /usr/local/bin/containerd-shim-runc-v2 -namespace default -id sleeper -address /run/containerd/containerd.sock
   5899    5876  \_ sleep 100000

Here is the sequence.

  1. containerd runs the shim with start. That instance (5867) starts another (5876) and exits. Only the second remains in the process list, with PID 1 as its parent.
  2. The shim calls runc create. --bundle specifies the directory containing the container configuration. --pid-file gives the path for the container process’s PID, --log gives the JSON log path, and --root tells runc where to store its state.
  3. The shim calls runc start, and runc exits again.
  4. The container process, sleep (5899), is a child of the shim.

Inspect the bundle directory

Look in the --bundle directory while the container is running.

b=/run/containerd/io.containerd.runtime.v2.task/default/sleeper
ls -l $b
total 24
-rw-r--r-- 1 root root  134 Nov 10 19:35 bootstrap.json
-rw-r--r-- 1 root root 2875 Nov 10 19:35 config.json
-rw-r--r-- 1 root root    4 Nov 10 19:35 init.pid
prwx------ 1 root root    0 Nov 10 19:35 log
-rw-r--r-- 1 root root    0 Nov 10 19:35 log.json
-rw------- 1 root root    2 Nov 10 19:35 options.json
drwxr-xr-x 1 root root 4096 Nov 10 19:35 rootfs
-rw------- 1 root root    0 Nov 10 19:35 runtime
lrwxrwxrwx 1 root root   17 Nov 10 19:35 s -> /run/containerd/s
-rw------- 1 root root   38 Nov 10 19:35 shim-binary-path
lrwxrwxrwx 1 root root   65 Nov 10 19:35 work -> /var/lib/containerd/io.containerd.runtime.v2.task/default/sleeper

runc uses config.json and rootfs. It writes init.pid and log.json according to --pid-file and --log. The shim owns the remaining files. Inspect the configuration containerd wrote and the mount at rootfs.

jq -c 'keys' $b/config.json
jq -c '.root, .process.args, .linux.cgroupsPath, [.linux.namespaces[].type]' $b/config.json
findmnt -no FSTYPE,OPTIONS $b/rootfs
["linux","mounts","ociVersion","process","root"]
{"path":"rootfs"}
["sleep","100000"]
"/default/sleeper"
["pid","ipc","uts","mount","network"]
overlay rw,relatime,lowerdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/27/fs,upperdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/28/fs,workdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/28/work,uuid=on,nouserxattr

config.json describes the container in the Open Container Initiative (OCI) format, which lets different projects’ container and image tools work together. The root.path points to the relative path rootfs, and the command matches what we gave ctr. The specification explains two observations from Part 1.

  • It lists five namespaces and omits cgroup, so the ctr container shared the host’s cgroup namespace.
  • It omits hostname. A new uts namespace starts with a copy of the host’s hostname, so the container had the same name.

cgroupsPath is /default/sleeper, the path we saw in /proc/<PID>/cgroup. The containerd snapshotter has already mounted OverlayFS at rootfs using the image layer and a writable layer. runc receives a ready-to-use directory and has no need to read the image.

runc stores its state under --root. The default is /run/runc, so to list containerd’s containers we must point it at the same directory containerd uses.

runc --root /run/containerd/runc/default list
runc list
ID          PID         STATUS      BUNDLE                                                          CREATED                          OWNER
sleeper     5899        running     /run/containerd/io.containerd.runtime.v2.task/default/sleeper   2026-11-10T19:35:58.956022895Z   root
ID          PID         STATUS      BUNDLE      CREATED     OWNER

Stop and remove the container

Stop the container, then stop strace and inspect the remaining calls. tail -n +5 skips the first four lines we already examined.

ctr task kill -s SIGKILL sleeper
ctr container rm sleeper
kill %1
grep -E 'execve\("[^"]*(runc|shim)' /tmp/exec.trace | sed -E 's/^([0-9]+) +execve\("[^"]*", \[(.*)\], 0x.*/\1 \2/; s/", "/ /g; s/"//g' | tail -n +5
rm /tmp/exec.trace
5939 runc --root /run/containerd/runc/default --log /run/containerd/io.containerd.runtime.v2.task/default/sleeper/log.json --log-format json kill sleeper 9
5952 runc --root /run/containerd/runc/default --log /run/containerd/io.containerd.runtime.v2.task/default/sleeper/log.json --log-format json delete sleeper
5958 /usr/local/bin/containerd-shim-runc-v2 -namespace default -address /run/containerd/containerd.sock -publish-binary /usr/local/bin/containerd -id sleeper -bundle /run/containerd/io.containerd.runtime.v2.task/default/sleeper delete
5966 runc --root /run/containerd/runc/default --log /run/containerd/io.containerd.runtime.v2.task/default/sleeper/log.json --log-format json delete --force sleeper

ctr task kill became runc kill sleeper 9, where 9 is SIGKILL. Removing the task became runc delete. containerd invokes the shim again with delete, and the shim calls runc delete --force to clean up whether or not the container still exists.

runc provides a set of commands over the bundle directory: create, start, kill, and delete. Each invocation is short-lived. Now let’s call those commands ourselves.


OCI bundle

The OCI specification calls the directory passed through --bundle a bundle. It contains config.json and the root filesystem referenced by root.path. That is all runc needs. Build one under /srv/bundle.

Prepare the root filesystem

We need Alpine’s file tree. Image layers are tar archives applied in order. The easiest way to get the merged tree is to use nerdctl create to create a container without starting it, then nerdctl export to produce its filesystem as a single tar archive. Extract it into rootfs and remove the temporary container. We will assemble the layers ourselves in Part 4.

mkdir -p /srv/bundle/rootfs
cd /srv/bundle
id=$(nerdctl create $img)
nerdctl export $id | tar -C rootfs -xf -
nerdctl rm $id > /dev/null
ls rootfs
du -sh rootfs
bin
dev
etc
home
lib
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
8.7M	rootfs

This is an ordinary directory on the host disk. It uses 8.7 MB and has no mounts.

config.json

runc can generate a template to save us writing config.json from scratch.

runc spec
ls -l
jq '.process' config.json
total 8
-rw-r--r--  1 root root 2500 Nov 10 19:36 config.json
drwxr-xr-x 19 root root 4096 Nov 10 19:36 rootfs
{
    "terminal": true,
    "user": {
        "uid": 0,
        "gid": 0
    },
    "args": [
        "sh"
    ],
    "env": [
        "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
        "TERM=xterm"
    ],
    "cwd": "/",
    "capabilities": {
        "bounding": [
            "CAP_AUDIT_WRITE",
            "CAP_KILL",
            "CAP_NET_BIND_SERVICE"
        ],
        "effective": [
            "CAP_AUDIT_WRITE",
            "CAP_KILL",
            "CAP_NET_BIND_SERVICE"
        ],
        "permitted": [
            "CAP_AUDIT_WRITE",
            "CAP_KILL",
            "CAP_NET_BIND_SERVICE"
        ]
    },
    "rlimits": [
        {
            "type": "RLIMIT_NOFILE",
            "hard": 1024,
            "soft": 1024
        }
    ],
    "noNewPrivileges": true
}

The process section describes the program and its privileges.

  • terminal gives the process a pseudoterminal for an interactive session.
  • user sets the UID and GID inside the container.
  • args, env, and cwd set the command, environment, and working directory.
  • capabilities controls privileges. Linux splits root privileges into capabilities such as changing the hostname, mounting filesystems, and binding ports below 1024. The template keeps three: CAP_KILL to signal other users’ processes, CAP_NET_BIND_SERVICE to bind low ports, and CAP_AUDIT_WRITE to write to the audit log. bounding sets a ceiling, permitted lists what the process may use, and effective lists what it can use now.
  • rlimits gives per-process limits, here a maximum of 1024 open files.
  • noNewPrivileges prevents acquiring new privileges, for example by executing a setuid program that would run as its owner.

Here are the remaining sections in brief.

jq -c '.root, .hostname' config.json
jq -r '.mounts[] | [.destination, .type, (.options // [] | join(","))] | @tsv' config.json | column -t
jq -c '.linux | keys, [.namespaces[].type], .resources' config.json
jq -c '.linux.maskedPaths, .linux.readonlyPaths' config.json
{"path":"rootfs","readonly":true}
"runc"
/proc           proc
/dev            tmpfs   nosuid,strictatime,mode=755,size=65536k
/dev/pts        devpts  nosuid,noexec,newinstance,ptmxmode=0666,mode=0620,gid=5
/dev/shm        tmpfs   nosuid,noexec,nodev,mode=1777,size=65536k
/dev/mqueue     mqueue  nosuid,noexec,nodev
/sys            sysfs   nosuid,noexec,nodev,ro
/sys/fs/cgroup  cgroup  nosuid,noexec,nodev,relatime,ro
["maskedPaths","namespaces","readonlyPaths","resources"]
["pid","network","ipc","uts","mount","cgroup"]
{"devices":[{"allow":false,"access":"rwm"}]}
["/proc/acpi","/proc/asound","/proc/kcore","/proc/keys","/proc/latency_stats","/proc/timer_list","/proc/timer_stats","/proc/sched_debug","/sys/firmware","/proc/scsi"]
["/proc/bus","/proc/fs","/proc/irq","/proc/sys","/proc/sysrq-trigger"]
  • root sets the filesystem root, which the template makes read-only.
  • hostname sets the hostname in the new uts namespace.
  • mounts sets up /proc for the new pid namespace, an empty tmpfs at /dev, pseudoterminals at /dev/pts, shared memory at /dev/shm, and message queues at /dev/mqueue. It mounts /sys and /sys/fs/cgroup read-only.
  • namespaces lists six namespaces. The template adds cgroup to the five we saw from containerd. There is no user namespace, so container root is host root with fewer capabilities.
  • resources sets cgroup limits. The template denies reads, writes, and creation (rwm) for all devices. runc adds exceptions for /dev/null, /dev/zero, /dev/urandom, and other devices ordinary programs need.
  • maskedPaths covers files and directories that expose host information with empty mounts. For example, /proc/kcore exposes host memory.
  • readonlyPaths keeps paths visible but prevents writes. An example is /proc/sys, which controls kernel settings.

Run the bundle

The template works as it is. runc run demo opens an interactive shell, which you can leave with exit. It requires a terminal. A script or an ssh session without -t has no terminal, so runc refuses.

time="2026-11-10T19:36:02Z" level=error msg="runc run failed: open /dev/tty: no such device or address"

Disable the terminal and set the command. Also set the cgroup path. Without cgroupsPath, runc creates a group named for the container alongside the launching session’s group, so the path depends on how you logged in. Edit config.json with jq.

jq '.process.terminal = false | .linux.cgroupsPath = "/lab/demo" | .process.args = ["sh", "-c", "cat /etc/alpine-release; hostname; ps; ip a; cat /proc/self/cgroup; touch /x"]' config.json > c.json && mv c.json config.json
runc run demo
echo "exit $?"
3.24.4
runc
PID   USER     TIME  COMMAND
    1 root      0:00 sh -c cat /etc/alpine-release; hostname; ps; ip a; cat /proc/self/cgroup; touch /x
    9 root      0:00 ps
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
0::/
touch: /x: Read-only file system
exit 1

demo is the runc container name and must be unique. The running container reflects config.json.

  • The files come from our rootfs and the name runc comes from hostname.
  • sh is PID 1 in its own pid namespace.
  • The only interface is lo. The new network namespace has yet to be connected. The CNI plugins did that for the containerd client in Part 1, and we will do it by hand in Part 6.
  • /proc/self/cgroup shows 0::/. The process sees its own group as the root of its cgroup namespace.
  • Creating a file in the root fails because of root.readonly.

runc run combines create and start, then waits for the process. It returns the process’s status. touch failed to create the file and sh returned 1.


The lifecycle from create to delete

The OCI specification defines runtime operations and the container states between them: creating, created, running, and stopped. Work through them as the shim does. The container command now writes a line to standard output and replaces itself with sleep.

jq '.process.args = ["sh", "-c", "echo started at $(date +%T); exec sleep 100000"]' config.json > c.json && mv c.json config.json
runc create demo > /srv/bundle/out.log 2>&1 < /dev/null
runc list
ls -l /run/runc/demo
pid=$(runc state demo | jq .pid)
ps -o pid,ppid,cmd -p $pid
cat /proc/$pid/cgroup
wc -c < out.log
ID          PID         STATUS      BUNDLE        CREATED                          OWNER
demo        6067        created     /srv/bundle   2026-11-10T19:36:02.558003626Z   root
total 4
prw--w--w- 1 root root    0 Nov 10 19:36 exec.fifo
-rw------- 1 root root 3364 Nov 10 19:36 state.json
    PID    PPID CMD
   6067       1 runc init
0::/lab/demo
0

Without a terminal, the container process inherits runc’s standard streams. We redirected them to a file.

After create, the namespaces and root mount exist, and the process is in /lab/demo. The configured command has yet to run. Another invocation of runc, runc init, waits inside the container on exec.fifo. A FIFO is a named pipe, and opening it for writing blocks until a reader opens it. That is why out.log is empty. runc create has exited, leaving PID 1 as the parent of runc init.

runc start demo
runc list
cat out.log
ps -o pid,ppid,cmd -p $pid
ID          PID         STATUS      BUNDLE        CREATED                          OWNER
demo        6067        running     /srv/bundle   2026-11-10T19:36:02.558003626Z   root
started at 19:36:02
    PID    PPID CMD
   6067       1 sleep 100000

runc start opens the pipe. runc init can proceed and replaces itself with the container command. PID 6067 now belongs to sleep, and exec.fifo disappears.

Inside the running container

runc exec launches another process in the same namespaces and cgroup. Inspect root’s privileges and the masked paths.

runc exec demo ps
runc exec demo sh -c 'cat /proc/1/cgroup; grep Cap /proc/self/status; hostname other; wc -c /proc/kcore; ls /sys/firmware | wc -l'
grep -E ' /proc/(kcore|sys) ' /proc/$pid/mountinfo
PID   USER     TIME  COMMAND
    1 root      0:00 sleep 100000
    8 root      0:00 ps
0::/
CapInh:	0000000000000000
CapPrm:	0000000020000420
CapEff:	0000000020000420
CapBnd:	0000000020000420
CapAmb:	0000000000000000
hostname: sethostname: Operation not permitted
0 /proc/kcore
0
307 399 0:64 /sys /proc/sys ro,relatime - proc proc rw
310 399 0:65 /null /proc/kcore rw,nosuid - tmpfs tmpfs rw,size=65536k,mode=755,inode64

/proc/self/status shows capabilities as a bitmask. 0x20000420 sets bits 5, 10, and 29, corresponding to CAP_KILL, CAP_NET_BIND_SERVICE, and CAP_AUDIT_WRITE from config.json. Changing the hostname requires CAP_SYS_ADMIN even for root. /proc/kcore is empty because the container’s /dev/null (/null on the /dev tmpfs) is mounted over it. /proc/sys was remounted read-only (ro), and /sys/firmware is empty. We will examine container privileges in Part 7.

Stop the container

runc kill demo KILL
sleep 1
runc state demo | jq .
ps -o pid,cmd -p $pid || echo "no process $pid"
runc delete demo
runc list
{
    "ociVersion": "1.3.0",
    "id": "demo",
    "pid": 0,
    "status": "stopped",
    "bundle": "/srv/bundle",
    "rootfs": "/srv/bundle/rootfs",
    "created": "2026-11-10T19:36:02.558003626Z",
    "owner": ""
}
    PID CMD
no process 6067
ID          PID         STATUS      BUNDLE      CREATED     OWNER

The container is stopped and its process is gone. After runc delete, the container and cgroup are gone too. The runc state has no exit status field. PID 1, systemd, received the exit status because it became the process’s parent when runc create exited.

Why containerd uses a shim

The shim fills in the lifecycle functions that bare runc leaves to its caller.

  • Parent process. The shim makes itself a subreaper with prctl and PR_SET_CHILD_SUBREAPER. Orphaned descendants are reparented to it, so it becomes the parent of sleep and receives its exit status. Shim source
  • Standard streams. We redirected container output to a file. The shim holds the streams and forwards them, for example to the container logs exposed by nerdctl.
  • Communication with containerd. The shim answers questions about the container and reports when it exits. -publish-binary from the trace identifies the program it uses to publish events. The shim can keep running independently of containerd.

Set limits in config.json

In Part 1, nerdctl turned --memory and --cpus into the linux.resources section. Write it ourselves with a 64 MiB memory limit and at most 20 processes in the group. The container prints the limits and tries to launch 30 sleep processes.

jq '.linux.resources.memory = {"limit": 67108864} | .linux.resources.pids = {"limit": 20} | .process.args = ["sh", "-c", "cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/pids.max; for i in $(seq 30); do sleep 60 & done"]' config.json > c.json && mv c.json config.json
runc run demo
echo "exit $?"
67108864
20
sh: can't fork: Resource temporarily unavailable
exit 2

runc wrote the limits to memory.max and pids.max under /lab/demo. The kernel refused to create the twenty-first process. The shell exited with an error, and the kernel killed the remaining sleep processes because PID 1 in their pid namespace had died. We will set up a cgroup without runc in Part 5.


Clean up

runc removed /lab/demo. Remove the parent /lab, the bundle, and the image.

cd /
rm -rf /srv/bundle
rmdir /sys/fs/cgroup/lab
ctr image rm $img
runc list
docker.io/library/alpine:3.24
ID          PID         STATUS      BUNDLE      CREATED     OWNER

Keep containerd, runc, and nerdctl installed.


Build the bundle with a script

make-bundle.sh builds a bundle from any image. It unpacks the filesystem into rootfs, runs runc spec, disables the terminal, and sets the command and the cgroup /lab/<directory-name>.

./make-bundle.sh docker.io/library/alpine:3.24 /srv/bundle sh -c 'hostname; ps'
cd /srv/bundle && runc run demo

Clean up as before by removing the bundle directory, /sys/fs/cgroup/lab, and the image.


References


Next, we remove runc too. We will create and enter namespaces with unshare and nsenter, switch roots with pivot_root, and mount /proc and /dev by hand.

Only registered users can leave a comment.

Sign in or register to leave a comment.