Linux Containers by Hand. Part 3: Building a container with unshare and pivot_root
All parts of the series “Linux Containers by Hand”In Part 2, runc built a container from config.json. It created namespaces, switched roots, mounted /proc and /dev, masked some paths, and made the root read-only. Today we will do the same with ordinary util-linux commands. Each setting in config.json comes down to one or more system calls.
config.json setting |
Command used here |
|---|---|
linux.namespaces |
unshare |
root.path |
mount --bind, pivot_root |
mounts |
mount -t proc, sysfs, tmpfs, devpts, mknod |
hostname |
hostname |
maskedPaths, readonlyPaths, root.readonly |
mount --bind, mount -o remount,ro |
runc exec |
nsenter |
Parts 5, 6, and 7 cover cgroups, networking, and root privileges. The script that builds this container in one command 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 |
| util-linux | 2.41.3, including unshare, nsenter, pivot_root, and lsns |
| containerd and nerdctl | 2.4.2, used only to retrieve the image files |
| Image | docker.io/library/alpine:3.24 |
Install containerd and nerdctl as in Part 1. Run all commands as root (sudo -i).
Try each namespace separately
The kernel provides three system calls for namespaces. clone() with CLONE_NEW* flags creates a new process in new namespaces. unshare() moves the caller into new namespaces. setns() joins an existing namespace. The unshare command calls unshare() and runs the requested program, while nsenter calls setns(). Try each namespace in turn.
uts: hostname
hostname
unshare --uts sh -c 'hostname box; hostname'
hostname
lincont-lab
box
lincont-lab
The hostname changed inside and stayed the same on the host. A new uts namespace starts with a copy of the host’s hostname, so the difference only appears after changing it with hostname.
pid: process IDs
unshare --pid sh -c 'echo $$; ps -o pid= -p $$; ps -o pid= -p $$'
7717
7717
sh: 1: Cannot fork
The shell sees its regular host PID, and the second ps fails to start. A running process cannot change its own pid namespace. unshare() changes the namespace for its future children. The shell’s first child, the first ps, became PID 1 and then exited. A PID namespace can accept no new processes once its PID 1 exits. With --fork, unshare forks and the requested program becomes PID 1.
unshare --pid --fork sh -c 'echo $$; ps -e | wc -l; ps -o pid,cmd -p 1'
1
138
PID CMD
1 /usr/lib/systemd/systemd --switched-root --system --deserialize=55
The shell sees itself as PID 1, but ps lists 137 host processes and sees systemd as PID 1. ps reads /proc, whose current mount shows the host’s pid namespace. We need a new /proc mount and a separate mount namespace to keep the change off the host. --mount-proc does both.
unshare --pid --fork --mount-proc sh -c 'echo $$; ps -e'
1
PID TTY TIME CMD
1 ? 00:00:00 sh
2 ? 00:00:00 ps
mount: mount points
findmnt -no PROPAGATION /
unshare --mount sh -c 'findmnt -no PROPAGATION /; mount -t tmpfs demo /mnt; findmnt /mnt'
findmnt /mnt || echo "no mount on /mnt"
shared
private
TARGET SOURCE FSTYPE OPTIONS
/mnt demo tmpfs rw,relatime,inode64
no mount on /mnt
A new mount namespace starts with copies of the host mounts. Mount propagation matters. systemd makes the root shared, which propagates mounts beneath it to its peers, including peers in other namespaces. Left as-is, a container mount would appear on the host. By default unshare makes the mounts in the new namespace private. The host therefore never saw our tmpfs at /mnt.
net: networking
unshare --net ip a
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
The new network namespace has only lo, initially DOWN. runc brought it up for us in Part 2.
ipc: interprocess communication
The ipc namespace isolates System V message queues, semaphores, and shared memory segments. Processes still use this older mechanism to exchange data by numeric key. Create a queue on the host and inspect it from the host and from the namespace.
ipcmk -Q
ipcs -q
unshare --ipc ipcs -q
ipcrm --all=msg
Message queue id: 2
------ Message Queues --------
key msqid owner perms used-bytes messages
0x06c4f18e 2 root 644 0 0
------ Message Queues --------
key msqid owner perms used-bytes messages
The host queue is absent in the new namespace.
cgroup: the path to a group
cat /proc/self/cgroup
unshare --cgroup cat /proc/self/cgroup
0::/user.slice/user-1000.slice/session-51.scope
0::/
A cgroup namespace changes the view of cgroup paths. The process stays in its current cgroup and sees it as /. Any resource limits still come from the group’s settings.
What else uses namespaces?
Namespaces are also used outside containers. lsns lists namespaces on the system. Here we look at uts.
lsns -t uts
NS TYPE NPROCS PID USER COMMAND
4026531838 uts 126 1 root /usr/lib/systemd/systemd --switched-root --system --deserialize=55
4026532121 uts 3 960 root ├─/bin/sh /usr/lib/systemd/scripts/chronyd-starter.sh -n -F 1
4026532134 uts 1 526 root ├─/usr/lib/systemd/systemd-udevd
4026532136 uts 1 971 polkitd ├─/usr/lib/polkit-1/polkitd --no-debug --log-level=notice
4026532137 uts 1 1043 syslog ├─/usr/sbin/rsyslogd -n -iNONE
4026532141 uts 1 978 root ├─/usr/lib/systemd/systemd-logind
4026532148 uts 1 3837 root └─/usr/libexec/fwupd/fwupd
These systemd services use ProtectHostname=. systemd gives them their own uts namespace to prevent them from changing the host’s name.
Prepare the root
Get the image files
runc receives an existing directory as the container root. Get one as in Part 2. nerdctl create creates a stopped container, and nerdctl export writes its filesystem as a tar archive.
img=docker.io/library/alpine:3.24
mkdir -p /srv/c3/rootfs
id=$(nerdctl create $img)
nerdctl export $id | tar -C /srv/c3/rootfs -xf -
nerdctl rm $id > /dev/null
ls -A /srv/c3/rootfs/dev /srv/c3/rootfs/proc /srv/c3/rootfs/sys
/srv/c3/rootfs/dev:
/srv/c3/rootfs/proc:
/srv/c3/rootfs/sys:
The image has empty /dev, /proc, and /sys directories. We will mount the filesystems there ourselves.
What chroot changes
chroot is the oldest way to change roots. It only changes the directory the process starts from when resolving paths beginning with /. Everything else is still shared with the host.
unshare --mount chroot /srv/c3/rootfs /bin/sh -c 'cat /etc/alpine-release; mount -t proc proc /proc; head -1 /proc/1/root/etc/os-release; ls /proc/1/root/srv'
3.24.4
PRETTY_NAME="Ubuntu 26.04.1 LTS"
c3
The shell is in Alpine, but /proc/1/root leads through the host’s systemd process to the Ubuntu filesystem, including our /srv/c3 directory. unshare --mount here only keeps the /proc mount off the host.
pivot_root
pivot_root changes the root mount of the mount namespace. It makes new_root the root mount and moves the previous root into put_old inside it. We can then unmount the old root to remove it from the namespace. Try the image directory.
unshare --mount sh -c 'cd /srv/c3/rootfs; mkdir .oldroot; pivot_root . .oldroot'
rmdir /srv/c3/rootfs/.oldroot
findmnt -n -T /srv/c3/rootfs -o TARGET
pivot_root: failed to change root from `.' to `.oldroot': Device or resource busy
/
It fails because /srv/c3/rootfs is a directory on the current root mount at /. Bind-mounting it over itself with mount --bind makes it a mount point in its own right.
Build the container
Use two terminals. In the first, launch a shell with all the new namespaces except user and time.
unshare --mount --uts --ipc --net --pid --cgroup --fork sh
The rest of the commands in this terminal run inside the future container. Make the new root a mount point and switch to it.
echo $$
r=/srv/c3/rootfs
mount --bind $r $r
cd $r
mkdir .oldroot
pivot_root . .oldroot
cd /
cat /etc/alpine-release
ls /.oldroot
1
3.24.4
bin
boot
cdrom
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
snap
srv
swap.img
sys
tmp
usr
var
The root is now Alpine, and the old Ubuntu root is under /.oldroot. The running shell is still the host’s sh because we started it before changing roots. Subsequent programs such as mount, ps, and ip are found in the new root and come from Alpine.
/proc and /sys
mount -t proc proc /proc
mount -t sysfs -o ro,nosuid,nodev,noexec sysfs /sys
ps
ls /sys/class/net
PID USER TIME COMMAND
1 root 0:00 sh
9 root 0:00 ps
lo
/proc now shows the processes in our pid namespace. Mounting sysfs associates it with the caller’s network namespace, so /sys/class/net shows only lo. Mount it read-only as runc does, because writes under /sys can change device settings.
/dev
Mount a small tmpfs at /dev and create device nodes by hand. A device node stores a major and minor number that the kernel uses to identify the device driver. For example, 1 3 identifies /dev/null. Use mknod to create them.
mount -t tmpfs -o nosuid,mode=755,size=64k tmpfs /dev
mknod -m 666 /dev/null c 1 3
mknod -m 666 /dev/zero c 1 5
mknod -m 666 /dev/full c 1 7
mknod -m 666 /dev/random c 1 8
mknod -m 666 /dev/urandom c 1 9
mknod -m 666 /dev/tty c 5 0
mkdir /dev/pts /dev/shm
mount -t devpts -o newinstance,ptmxmode=0666,mode=0620 devpts /dev/pts
ln -s pts/ptmx /dev/ptmx
mount -t tmpfs -o nosuid,nodev,mode=1777 shm /dev/shm
ln -s /proc/self/fd /dev/fd
ln -s /proc/self/fd/0 /dev/stdin
ln -s /proc/self/fd/1 /dev/stdout
ln -s /proc/self/fd/2 /dev/stderr
ls -l /dev
total 0
lrwxrwxrwx 1 root root 13 Nov 10 20:04 fd -> /proc/self/fd
crw-rw-rw- 1 root root 1, 7 Nov 10 20:04 full
crw-rw-rw- 1 root root 1, 3 Nov 10 20:04 null
lrwxrwxrwx 1 root root 8 Nov 10 20:04 ptmx -> pts/ptmx
drwxr-xr-x 2 root root 0 Nov 10 20:04 pts
crw-rw-rw- 1 root root 1, 8 Nov 10 20:04 random
drwxrwxrwt 2 root root 40 Nov 10 20:04 shm
lrwxrwxrwx 1 root root 15 Nov 10 20:04 stderr -> /proc/self/fd/2
lrwxrwxrwx 1 root root 15 Nov 10 20:04 stdin -> /proc/self/fd/0
lrwxrwxrwx 1 root root 15 Nov 10 20:04 stdout -> /proc/self/fd/1
crw-rw-rw- 1 root root 5, 0 Nov 10 20:04 tty
crw-rw-rw- 1 root root 1, 9 Nov 10 20:04 urandom
crw-rw-rw- 1 root root 1, 5 Nov 10 20:04 zero
- The six character devices (lines beginning with
c) are the minimum ordinary programs need. - Mounting
devptswithnewinstanceprovides independent pseudoterminals. Programs open/dev/ptmxto allocate one. /dev/shmprovides shared memory for container processes./dev/fd,/dev/stdin,/dev/stdout, and/dev/stderrlink to the process’s open files in/proc.
Hide host paths and make the root read-only
Unmount the old root, set the hostname, enable lo, mask paths and make others read-only as maskedPaths and readonlyPaths did, and remount the root read-only.
umount -l /.oldroot
rmdir /.oldroot
hostname box
ip link set lo up
mount --bind /dev/null /proc/kcore
mount --bind /proc/sys /proc/sys
mount -o remount,bind,ro /proc/sys
mount -o remount,bind,ro /
cat /proc/mounts
/dev/sda2 / ext4 ro,relatime 0 0
proc /proc proc rw,relatime 0 0
sysfs /sys sysfs ro,nosuid,nodev,noexec,relatime 0 0
tmpfs /dev tmpfs rw,nosuid,relatime,size=64k,mode=755,inode64 0 0
devpts /dev/pts devpts rw,relatime,mode=620,ptmxmode=666 0 0
shm /dev/shm tmpfs rw,nosuid,nodev,relatime,inode64 0 0
tmpfs /proc/kcore tmpfs rw,nosuid,relatime,size=64k,mode=755,inode64 0 0
proc /proc/sys proc ro,relatime 0 0
umount -l immediately detaches the old root even though it is busy because our shell executable lives there. The container mount table now has eight lines. Only the filesystem backing the image directory (/dev/sda2) remains visible from the host, and it is mounted read-only. A bind mount of /dev/null from our tmpfs hides /proc/kcore. /proc/sys is remounted read-only. Check the result.
hostname
ip a
cat /proc/self/cgroup
touch /x
wc -c /proc/kcore
box
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
0 /proc/kcore
This looks like the container we built with runc.
View the container from the host
In the second terminal, find the container process. Its PID 1 is a child of unshare.
pid=$(pgrep -P $(pgrep -n -x unshare))
ps -o pid,ppid,cmd -p $(pgrep -n -x unshare),$pid
for n in cgroup ipc mnt net pid uts; do
printf '%-6s host %-14s container %s\n' $n "$(readlink /proc/1/ns/$n | sed 's/.*://')" "$(readlink /proc/$pid/ns/$n | sed 's/.*://')"
done
cat /proc/$pid/cgroup
PID PPID CMD
7776 7699 unshare --mount --uts --ipc --net --pid --cgroup --fork sh
7778 7776 sh
cgroup host [4026531835] container [4026532150]
ipc host [4026531839] container [4026532144]
mnt host [4026531832] container [4026532142]
net host [4026531833] container [4026532151]
pid host [4026531836] container [4026532149]
uts host [4026531838] container [4026532143]
0::/user.slice/user-1000.slice/session-51.scope
All six namespaces are separate. The process is still in the cgroup of the SSH session that started unshare. Its own cgroup namespace changed only how it sees the path, and we have applied no container limits.
nsenter
nsenter does the same job as runc exec. It joins a running process’s namespaces and executes a command. -a selects all of them.
nsenter -t $pid -a sh -c 'cat /etc/alpine-release; hostname; ip a; cat /proc/self/cgroup'
nsenter -t $pid -u hostname
nsenter -t $pid -m cat /etc/alpine-release
3.24.4
box
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::/
box
3.24.4
You can join a single namespace too. With -u, the host’s hostname command displayed the container name. With -m, the command uses the mount namespace’s root, which our pivot_root switched to Alpine.
Check the remaining privileges
Return to the first terminal and inspect the privileges.
grep CapEff /proc/self/status
mount -o remount,rw /
touch /x && ls -l /x
rm /x
mount -o remount,bind,ro /
CapEff: 000001ffffffffff
-rw-r--r-- 1 root root 0 Nov 10 20:04 /x
The all-ones mask means the process has all root capabilities. A single mount command can therefore make the read-only root writable again. runc kept only three capabilities in Part 2, excluding CAP_SYS_ADMIN, which mount requires. Part 7 covers privileges, Part 5 covers cgroup limits, and Part 6 covers networking.
Stop the container
In the first terminal, type exit. The shell is PID 1 in its pid namespace. When it exits, the kernel kills the remaining processes, and the mount namespace disappears with its mounts.
A plain kill from the host has no effect.
kill $pid; sleep 1; ps -o pid= -p $pid && echo "still alive"
kill -KILL $pid; sleep 1
ps -o pid= -p $pid || echo "gone"
findmnt -n /srv/c3/rootfs || echo "no mounts left on host"
7778
still alive
gone
no mounts left on host
The namespace’s PID 1 receives only signals for which it installed handlers, and this shell has no SIGTERM handler. SIGKILL and SIGSTOP from an ancestor namespace are exceptions, so kill -KILL worked. The mounts existed only inside the container and need no host cleanup.
Clean up
rm -rf /srv/c3
nerdctl rmi $img > /dev/null
Keep containerd, runc, and nerdctl installed.
Run everything with a script
container.sh does this in one command and starts a shell or a command of your choice inside the container.
./container.sh /srv/c3/rootfs sh -c 'hostname; ps; cat /proc/mounts'
The script follows the order runc uses. It mounts everything beneath the image directory before switching roots, then calls pivot_root . .. The old root stacks on top of the new one, and umount -l . detaches it immediately. No .oldroot directory is needed. The script needs only sh and umount from the image. runc source
References
- Namespaces, PID 1, and mount propagation. namespaces(7), pid_namespaces(7), mount_namespaces(7)
- util-linux commands. unshare(1), nsenter(1), lsns(8)
- Changing the root. pivot_root(2), chroot(2)
- Device numbers. Linux allocated devices
- Services with their own
utsnamespace. systemd.exec: ProtectHostname= - How runc prepares the root. runc rootfs source
Next, we assemble the container root from image layers with OverlayFS, without nerdctl export.
Only registered users can leave a comment.
Sign in or register to leave a comment.