Linux Containers by Hand. Part 1: Installing containerd without Docker or Kubernetes
All parts of the series “Linux Containers by Hand”In Kubernetes for Beginners, containers were the building blocks of a cluster. In Part 4, we installed containerd as a kubeadm dependency and let kubelet manage the containers. This series goes down the stack, removing one layer of tooling at a time until we have a C program asking the kernel directly for everything that makes a process a container.
Today we start with Ubuntu and manually install containerd, runc, container networking, and nerdctl. We will run our first container, inspect it from the host, give it network access, publish a port, mount host files and directories, and limit memory and CPU usage.
The installation script and network configuration are 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, 8 GB RAM, and a 32 GB disk |
| OS | Ubuntu Server 26.04.1, kernel 7.0.0 |
| containerd | 2.4.2 |
| runc | 1.5.2 |
| CNI plugins | 1.10.0 |
| nerdctl | 2.4.2 |
| Images | docker.io/library/alpine:3.24, docker.io/library/nginx:1.30-alpine |
This is a fresh machine that has never had Docker or Kubernetes installed. Run all commands as root (sudo -i).
Here is what we will have by the end of this part.
nerdctl ctr ──────► CNI bridge and portmap plugins
│ │ bridge, veth, addresses, iptables
└───────┬────────┘
▼ /run/containerd/containerd.sock
┌─ containerd (systemd service) ────────────┐
│ images and layers: OverlayFS │
└──────────┬────────────────────────────────┘
▼
containerd-shim-runc-v2 (one shim per container)
│
▼
runc creates the container and exits
│
▼
container process: namespaces, cgroup, own root
At the top are two clients. ctr ships with containerd, and nerdctl offers familiar Docker commands. containerd stores images and unpacks layers. runc creates the container, and the shim supervises it while it runs.
What the kernel already provides
Windows Server requires a separate feature for containers. Linux already has the necessary mechanisms in its kernel. Three of them underpin the containers in this lab.
- Namespaces give a process its own view of shared resources, including process IDs, network interfaces, the hostname, and mount points.
- Control groups (cgroups) organize processes in a hierarchy for resource accounting and limits.
- OverlayFS combines the image layers and the container’s writable layer into a single filesystem view.
Let’s check what is available.
command -v containerd runc docker ctr || echo none
stat -fc %T /sys/fs/cgroup
cat /sys/fs/cgroup/cgroup.controllers
modinfo -F filename overlay
ls -l /proc/self/ns
none
cgroup2fs
cpuset cpu io memory hugetlb pids rdma misc dmem
/lib/modules/7.0.0-43-generic/kernel/fs/overlayfs/overlay.ko.zst
total 0
lrwxrwxrwx 1 root root 0 Nov 10 12:24 cgroup -> cgroup:[4026531835]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 ipc -> ipc:[4026531839]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 mnt -> mnt:[4026531832]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 net -> net:[4026531833]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 pid -> pid:[4026531836]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 pid_for_children -> pid:[4026531836]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 time -> time:[4026531834]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 time_for_children -> time:[4026531834]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 user -> user:[4026531837]
lrwxrwxrwx 1 root root 0 Nov 10 12:24 uts -> uts:[4026531838]
There are no container tools installed. cgroup2fs means the system uses cgroup v2 with a unified hierarchy. OverlayFS is a kernel module, which the containerd service will load at startup. /proc/self/ns shows the namespaces of the ls process itself. Each link identifies a namespace by number. We will compare these numbers with the container’s shortly.
containerd
Download and verify containerd
The containerd project publishes binaries and checksums on GitHub.
cd /tmp
v=2.4.2
base=https://github.com/containerd/containerd/releases/download/v$v
curl -sSLO $base/containerd-$v-linux-amd64.tar.gz
curl -sSLO $base/containerd-$v-linux-amd64.tar.gz.sha256sum
sha256sum -c containerd-$v-linux-amd64.tar.gz.sha256sum
tar -tzf containerd-$v-linux-amd64.tar.gz
tar -xzf containerd-$v-linux-amd64.tar.gz -C /usr/local
containerd --version
containerd-2.4.2-linux-amd64.tar.gz: OK
bin/
bin/containerd
bin/containerd-shim-runc-v2
bin/containerd-stress
bin/ctr
containerd github.com/containerd/containerd/v2 v2.4.2 b7a25261e029d68978bbf290df0a62fc819b3c51
The archive contains four programs.
containerdis the daemon.ctris a debugging client that exposes the containerd API directly.containerd-shim-runc-v2is the shim. containerd starts one for each container. The shim invokes runc and stays on as the container process’s parent.containerd-stressis a load-testing tool we will leave aside.
Set up the service
The systemd unit is available in the project repository. Put it where systemd looks for locally installed services.
mkdir -p /usr/local/lib/systemd/system
curl -sSL -o /usr/local/lib/systemd/system/containerd.service https://raw.githubusercontent.com/containerd/containerd/v$v/containerd.service
grep -vE '^#|^$' /usr/local/lib/systemd/system/containerd.service
[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target dbus.service
[Service]
ExecStartPre=-/sbin/modprobe overlay
ExecStart=/usr/local/bin/containerd
Type=notify
Delegate=yes
KillMode=process
Restart=always
RestartSec=5
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
OOMScoreAdjust=-999
[Install]
WantedBy=multi-user.target
KillMode=process tells systemd to stop only the daemon, so restarting containerd leaves running containers alone. Delegate=yes lets the service create cgroups beneath its own group. OOMScoreAdjust=-999 makes containerd one of the last processes the kernel will choose to kill under memory pressure.
runc
runc creates the container. It is distributed by a separate project.
r=1.5.2
curl -sSLO https://github.com/opencontainers/runc/releases/download/v$r/runc.amd64
curl -sSLO https://github.com/opencontainers/runc/releases/download/v$r/runc.sha256sum
grep ' \*\?runc.amd64$' runc.sha256sum
sha256sum runc.amd64
install -m 755 runc.amd64 /usr/local/sbin/runc
runc --version
599f6f94ff8c5057241eff0d54c3c74f95c34935b6457b33fe545defc61e9488 runc.amd64
599f6f94ff8c5057241eff0d54c3c74f95c34935b6457b33fe545defc61e9488 runc.amd64
runc version 1.5.2
commit: v1.5.2-0-g29dd3dc
spec: 1.3.0
go: go1.26.8
libseccomp: 2.6.1
libpathrs: 0.2.6
The checksums match. The spec line gives the version of the Open Container Initiative (OCI) specification. It is a common format for describing containers and images so tools from different projects can interoperate. containerd passes an OCI configuration to runc. In Part 2 we will write one by hand.
Configure containerd
containerd can run with its built-in defaults. Generating the configuration file makes those values easy to inspect.
mkdir -p /etc/containerd
containerd config default > /etc/containerd/config.toml
grep -E "^root|^state|snapshotter = 'o|default_runtime_name|bin_dirs|conf_dir|^ *platforms|SystemdCgroup|^ +address = '/run/containerd/containerd.sock'" /etc/containerd/config.toml
root = '/var/lib/containerd'
state = '/run/containerd'
snapshotter = 'overlayfs'
default_runtime_name = 'runc'
SystemdCgroup = false
bin_dirs = ['/opt/cni/bin']
conf_dir = '/etc/cni/net.d'
platforms = ['linux/amd64']
address = '/run/containerd/containerd.sock'
rootstores images, layers, and metadata.stateholds transient data on a memory-backed filesystem.snapshotter = 'overlayfs'selects how image layers become the container filesystem.default_runtime_nameandSystemdCgroupare CRI settings used by kubelet.ctrand nerdctl choose these values themselves.bin_dirsandconf_dirlocate the CNI plugins and their configuration. These directories do not exist yet.addressis the Unix socket clients use to talk to containerd.
Start the service.
systemctl daemon-reload
systemctl enable --now containerd
systemctl status containerd --no-pager | head -12
ctr version
● containerd.service - containerd container runtime
Loaded: loaded (/usr/local/lib/systemd/system/containerd.service; enabled; preset: enabled)
Active: active (running) since Tue 2026-11-10 12:24:35 UTC; 2s ago
Invocation: 5b981a18b399438ab17b53a605d00fa1
Docs: https://containerd.io
Process: 1833 ExecStartPre=/sbin/modprobe overlay (code=exited, status=0/SUCCESS)
Main PID: 1835 (containerd)
Tasks: 9
Memory: 14.6M (peak: 15.4M)
CPU: 38ms
CGroup: /system.slice/containerd.service
└─1835 /usr/local/bin/containerd
Client:
Version: v2.4.2
Revision: b7a25261e029d68978bbf290df0a62fc819b3c51
Go version: go1.27.2
Server:
Version: v2.4.2
Revision: b7a25261e029d68978bbf290df0a62fc819b3c51
UUID: 42e4d236-ebe3-4877-ac02-7cb96b86ac31
Run the first container with ctr
ctr needs a fully qualified image name, including the registry, so we will store it in a variable. pull reports download progress for every object. The output below omits those progress lines.
img=docker.io/library/alpine:3.24
ctr image pull $img
ctr image ls
REF TYPE DIGEST SIZE PLATFORMS LABELS
docker.io/library/alpine:3.24 application/vnd.oci.image.index.v1+json sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf 3.7 MiB linux/386,linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64/v8,linux/ppc64le,linux/riscv64,linux/s390x -
The image index lists variants for several platforms. containerd downloaded the linux/amd64 variant, which takes up 3.7 MiB compressed. Now run it.
ctr run --rm $img hello sh -c 'cat /etc/alpine-release; hostname; id -u; uname -r; ip a; ps; cat /etc/resolv.conf'
uname -r
3.24.4
lincont-lab
0
7.0.0-43-generic
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
PID USER TIME COMMAND
1 root 0:00 sh -c cat /etc/alpine-release; hostname; id -u; uname -r; ip a; ps; cat /etc/resolv.conf
12 root 0:00 ps
cat: can't open '/etc/resolv.conf': No such file or directory
7.0.0-43-generic
Here are five things to notice.
- The files come from Alpine even though the host runs Ubuntu. The container has its own filesystem root.
- The kernel is still the host’s
7.0.0-43-generic. - The
shprocess sees itself as PID 1 and sees only itself andps. - The only interface is
lo.ctrneeds an explicit request to configure networking. - The hostname matches the host, and there is no
/etc/resolv.conf. Docker would set both up automatically.ctronly does what we ask it to.
View the container from the host
Start a container in the background and inspect it from outside.
ctr run -d $img sleeper sleep 100000
ctr container ls
ctr task ls
ps -o pid,ppid,user,cmd --forest -e | grep -E 'containerd|sleep' | grep -v grep
pgrep -a runc || echo 'no runc process'
CONTAINER IMAGE RUNTIME
sleeper docker.io/library/alpine:3.24 io.containerd.runc.v2
TASK PID STATUS
sleeper 2292 RUNNING
1835 1 root /usr/local/bin/containerd
2269 1 root /usr/local/bin/containerd-shim-runc-v2 -namespace default -id sleeper -address /run/containerd/containerd.sock
2292 2269 root \_ sleep 100000
no runc process
The container is a sleep process with PID 2292 in the host process list. containerd distinguishes a container, the image reference and specification, from a task, the running workload.
Look at the process tree. The shim is the parent of the container process, and the shim itself has PID 1 as its parent. That is why restarting containerd leaves the container running. runc created the container and exited.
Inside the container, the same process looks different.
ctr task exec --exec-id p1 sleeper ps
PID USER TIME COMMAND
1 root 0:00 sleep 100000
8 root 0:00 ps
The host sees PID 2292, and the container sees PID 1. Let’s compare their namespaces. Use the PID from ctr task ls in place of 2292.
pid=2292
for n in cgroup ipc mnt net pid user uts time; do
printf '%-7s 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
cgroup host [4026531835] container [4026531835]
ipc host [4026531839] container [4026532194]
mnt host [4026531832] container [4026532192]
net host [4026531833] container [4026532199]
pid host [4026531836] container [4026532198]
user host [4026531837] container [4026531837]
uts host [4026531838] container [4026532193]
time host [4026531834] container [4026531834]
0::/default/sleeper
The container has its own ipc (message queues and shared memory), mnt (mount points), net (network), pid (process IDs), and uts (hostname) namespaces. It shares the others with the host. Since it shares the user namespace, root in the container is also root on the host. We will change that in Part 7.
The host can also see the container’s root through /proc/<PID>/root. The process’s mount table shows where that root comes from.
cat /proc/$pid/root/etc/alpine-release
grep ' / / ' /proc/$pid/mountinfo
3.24.4
404 323 0:55 / / rw,relatime - overlay overlay rw,lowerdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/3/fs,upperdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/5/fs,workdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/5/work,uuid=on,nouserxattr
The root is an OverlayFS mount. lowerdir is the unpacked image layer and upperdir is the container’s writable layer. We will build a root like this in Part 4. Remove the container.
ctr task kill -s SIGKILL sleeper
ctr container rm sleeper
Networking with CNI and the bridge plugin
How a container gets network access
CNI, the Container Network Interface, specifies how a runtime requests networking for a container. Each plugin is an executable. The runtime supplies the command (ADD to attach, DEL to detach, CHECK to check), container ID, and network namespace path in environment variables, and sends the JSON network configuration on standard input. The plugin configures the network and prints a JSON result with the assigned addresses.
In ordinary containerd use, the client invokes the plugins. Here that means ctr or nerdctl. When kubelet uses containerd through CRI, containerd invokes them itself.
v=1.10.0
f=cni-plugins-linux-amd64-v$v.tgz
curl -sSLO https://github.com/containernetworking/plugins/releases/download/v$v/$f
curl -sSLO https://github.com/containernetworking/plugins/releases/download/v$v/$f.sha256
sha256sum -c $f.sha256
mkdir -p /opt/cni/bin /etc/cni/net.d
tar -xzf $f -C /opt/cni/bin
ls -C /opt/cni/bin
cni-plugins-linux-amd64-v1.10.0.tgz: OK
LICENSE bridge firewall ipvlan portmap static vlan
README.md dhcp host-device loopback ptp tap vrf
bandwidth dummy host-local macvlan sbr tuning
We need three plugins. bridge connects the container to a bridge on the host. host-local assigns addresses and records them in files. portmap publishes ports.
Configure the network
Put the network configuration, 10-lab.conflist, in /etc/cni/net.d.
cat > /etc/cni/net.d/10-lab.conflist <<'EOF'
{
"cniVersion": "1.0.0",
"name": "lab",
"plugins": [
{
"type": "bridge",
"bridge": "lab0",
"isGateway": true,
"ipMasq": true,
"ipam": {
"type": "host-local",
"ranges": [
[{ "subnet": "172.30.0.0/16", "gateway": "172.30.0.1" }]
],
"routes": [
{ "dst": "0.0.0.0/0" }
]
}
},
{
"type": "portmap",
"capabilities": { "portMappings": true }
}
]
}
EOF
pluginslists the plugins to call in order. That is why the file uses the.conflistextension.bridgenames the software switch on the host to which containers connect.isGatewayassigns a gateway address to the bridge so the host can route traffic for the containers.ipMasqenables network address translation (NAT). The host replaces the container’s internal source address with its own and translates replies on the way back, just as a home router does.ipamdefines the subnet, gateway, and default route. The subnet must avoid overlap with any networks the containers need to reach.capabilitiestellsportmapto accept the list of ports to publish from the runtime.
Connect a container
Check the host before the first run.
ip -br link
sysctl net.ipv4.ip_forward
iptables -t nat -S
lo UNKNOWN 00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
eth0 UP 00:15:5d:0a:00:31 <BROADCAST,MULTICAST,UP,LOWER_UP>
net.ipv4.ip_forward = 0
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
There is no bridge yet. Forwarding between interfaces is disabled and the nat table is empty. iptables is an interface to the kernel’s packet filtering and address translation rules. Run the container with --cni. ping sends ICMP echo requests, and the destination responds with echo replies.
img=docker.io/library/alpine:3.24
ctr run --rm --cni $img net1 sh -c 'ip -4 a show eth0; ip route; ping -c 2 1.1.1.1'
2: eth0@if4: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP qlen 1000
inet 172.30.0.2/16 brd 172.30.255.255 scope global eth0
valid_lft forever preferred_lft forever
default via 172.30.0.1 dev eth0
172.30.0.0/16 dev eth0 scope link src 172.30.0.2
PING 1.1.1.1 (1.1.1.1): 56 data bytes
64 bytes from 1.1.1.1: seq=0 ttl=54 time=9.543 ms
64 bytes from 1.1.1.1: seq=1 ttl=54 time=9.658 ms
--- 1.1.1.1 ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 9.543/9.600/9.658 ms
The container now has an eth0 address from our subnet, and the external address responds. Start a container in the background to inspect its network from the host. nsenter runs a command in the namespaces of the specified process.
ctr run -d --cni $img net2 sleep 100000
pid=$(ctr task ls | awk '$1=="net2"{print $2}')
nsenter -t $pid -n ip -br a
ip -br link
bridge link
ip -br -4 a show lab0
sysctl net.ipv4.ip_forward
ls /var/lib/cni/networks/lab/
cat /var/lib/cni/networks/lab/172.30.0.3; echo
lo UNKNOWN 127.0.0.1/8 ::1/128
eth0@if5 UP 172.30.0.3/16 fe80::3464:1ff:feab:3d24/64
lo UNKNOWN 00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
eth0 UP 00:15:5d:0a:00:31 <BROADCAST,MULTICAST,UP,LOWER_UP>
lab0 UP 4e:7a:2f:9f:52:2d <BROADCAST,MULTICAST,UP,LOWER_UP>
veth213a7b50@if2 UP 3e:d5:89:0c:38:18 <BROADCAST,MULTICAST,UP,LOWER_UP>
5: veth213a7b50@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master lab0 state forwarding priority 32 cost 2
lab0 UP 172.30.0.1/16
net.ipv4.ip_forward = 1
172.30.0.3
last_reserved_ip.0
lock
default-net2
eth0
The bridge plugin created lab0, gave it the gateway address, and enabled forwarding. It also made a veth pair: two virtual interfaces connected like the ends of a cable. One end became eth0 inside the container. The other, veth213a7b50, is attached to the bridge. eth0@if5 and 5: veth... identify the peers. host-local assigned the address. The file named for that address contains the container ID. We will build this setup with ip commands in Part 6.
Now inspect NAT.
iptables -t nat -S | grep -v '^-P'
-N CNI-73d550a73f3c63296d8ba70e
-N CNI-78f286cec500cab9b162c658
-A POSTROUTING -s 172.30.0.2/32 -m comment --comment "name: \"lab\" id: \"default-net1\"" -j CNI-73d550a73f3c63296d8ba70e
-A POSTROUTING -s 172.30.0.3/32 -m comment --comment "name: \"lab\" id: \"default-net2\"" -j CNI-78f286cec500cab9b162c658
-A CNI-73d550a73f3c63296d8ba70e -d 172.30.0.0/16 -m comment --comment "name: \"lab\" id: \"default-net1\"" -j ACCEPT
-A CNI-73d550a73f3c63296d8ba70e ! -d 224.0.0.0/4 -m comment --comment "name: \"lab\" id: \"default-net1\"" -j MASQUERADE
-A CNI-78f286cec500cab9b162c658 -d 172.30.0.0/16 -m comment --comment "name: \"lab\" id: \"default-net2\"" -j ACCEPT
-A CNI-78f286cec500cab9b162c658 ! -d 224.0.0.0/4 -m comment --comment "name: \"lab\" id: \"default-net2\"" -j MASQUERADE
Each container gets a chain. Packets destined for the subnet pass through as they are. For other destinations, MASQUERADE replaces the source address with one from the host. There are still rules for net1 even though it has already exited. Remove the second container and count again.
ctr task kill -s SIGKILL net2
ctr container rm net2
ip -br link | grep -c veth
ls /var/lib/cni/networks/lab/
iptables -t nat -S | grep -c 'CNI-'
0
last_reserved_ip.0
lock
8
The veth pairs went away with the network namespaces, and the addresses were released. Eight lines of rules remained. The ctr source shows that it calls DEL with an empty network namespace path when the container exits. In that case, the bridge plugin only releases the address. A container started with -d behaves the same way. This is fine for a quick test, but the rules keep accumulating until we remove them or reboot. Delete the chains named with 24 hexadecimal digits and the rules that jump to them.
iptables-save -t nat | grep -v 'CNI-[0-9a-f]\{24\}' | iptables-restore
iptables -t nat -S | grep -c 'CNI-'
0
DNS
DNS resolves names such as example.com to addresses. A ctr container lacks /etc/resolv.conf, so it has no DNS server configured.
ctr run --rm --cni $img net3 nslookup -type=a cloudflare.com
nslookup: read: Connection refused
nslookup: read: Connection refused
;; connection timed out; no servers could be reached
Ubuntu’s /etc/resolv.conf points to a file listing 127.0.0.53, where the host’s systemd-resolved listens. That address inside the container reaches its own loopback interface. Mount the adjacent file with the actual DNS servers.
ctr run --rm --cni --mount type=bind,src=/run/systemd/resolve/resolv.conf,dst=/etc/resolv.conf,options=rbind:ro $img net4 nslookup -type=a cloudflare.com
iptables-save -t nat | grep -v 'CNI-[0-9a-f]\{24\}' | iptables-restore
Server: 192.168.10.1
Address: 192.168.10.1:53
Non-authoritative answer:
Name: cloudflare.com
Address: 104.16.133.229
Name: cloudflare.com
Address: 104.16.132.229
nerdctl
ctr is handy for testing, but leaves image names, --cni, DNS, and rule cleanup to us. nerdctl is a containerd client with Docker commands such as run, ps, exec, -p, and -v. The archive contains nerdctl and two rootless setup scripts. Extract just the binary.
v=2.4.2
f=nerdctl-$v-linux-amd64.tar.gz
curl -sSLO https://github.com/containerd/nerdctl/releases/download/v$v/$f
curl -sSLO https://github.com/containerd/nerdctl/releases/download/v$v/SHA256SUMS
grep " $f\$" SHA256SUMS
sha256sum $f
tar -xzf $f -C /usr/local/bin nerdctl
nerdctl info | head -20
nerdctl network ls
41a66995888043c0ba05f8061574eaba1b9e06b9b21c2a238215179df2728d3f nerdctl-2.4.2-linux-amd64.tar.gz
41a66995888043c0ba05f8061574eaba1b9e06b9b21c2a238215179df2728d3f nerdctl-2.4.2-linux-amd64.tar.gz
Client:
Namespace: default
Debug Mode: false
Server:
Server Version: v2.4.2
Storage Driver: overlayfs
Logging Driver: json-file
Cgroup Driver: systemd
Cgroup Version: 2
Plugins:
Log: fluentd journald json-file none syslog
Storage: native overlayfs
Security Options:
apparmor
seccomp
Profile: builtin
cgroupns
Kernel Version: 7.0.0-43-generic
Operating System: Ubuntu 26.04.1 LTS
NETWORK ID NAME FILE
lab /etc/cni/net.d/10-lab.conflist
host
none
nerdctl found containerd through its socket and the lab network in the CNI directory. Cgroup Driver: systemd means systemd will create the container’s cgroup. Security Options shows a seccomp system call filter and a separate cgroup namespace. ctr adds neither by default. nerdctl sets up networking through OCI hooks. It writes the nerdctl internal oci-hook createRuntime and postStop commands into the specification, and runc invokes them when creating and removing the container.
Publish a port
Start nginx and publish its port 80 on port 8080 of the host. The output omits image download progress.
nerdctl run -d --name web -p 8080:80 docker.io/library/nginx:1.30-alpine
nerdctl ps
nerdctl network ls
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/
nerdctl inspect web | jq -r '.[0].NetworkSettings.Networks | to_entries[] | .key + " " + .value.IPAddress'
e970ec8be4f014777e29a755820987cfb8dc8232f9a95eb39d3faa9f23ebd145
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e970ec8be4f0 docker.io/library/nginx:1.30-alpine "/docker-entrypoint.…" 2 seconds ago Up 0.0.0.0:8080->80/tcp web
NETWORK ID NAME FILE
lab /etc/cni/net.d/10-lab.conflist
17f29b073143 bridge /etc/cni/net.d/nerdctl-bridge.conflist
host
none
200
bridge 10.4.0.2
nerdctl used its default network, bridge. It created the network on first use with a nerdctl0 bridge and the 10.4.0.0/24 subnet, and wrote nerdctl-bridge.conflist. Use --net lab to attach to our other network.
The page is also reachable from another machine on the network.
curl -s -o /dev/null -w '%{http_code}\n' http://192.168.10.31:8080/
200
The portmap plugin publishes the port using iptables rules.
iptables -t nat -S | grep 8080
-A CNI-DN-dbe261037652eb4e0012b -s 10.4.0.0/24 -p tcp -m tcp --dport 8080 -j CNI-HOSTPORT-SETMARK
-A CNI-DN-dbe261037652eb4e0012b -s 127.0.0.1/32 -p tcp -m tcp --dport 8080 -j CNI-HOSTPORT-SETMARK
-A CNI-DN-dbe261037652eb4e0012b -p tcp -m tcp --dport 8080 -j DNAT --to-destination 10.4.0.2:80
-A CNI-HOSTPORT-DNAT -p tcp -m comment --comment "dnat name: \"bridge\" id: \"default-e970ec8be4f014777e29a755820987cfb8dc8232f9a95eb39d3faa9f23ebd145\"" -m multiport --dports 8080 -j CNI-DN-dbe261037652eb4e0012b
The main rule is DNAT. Connections to the host’s port 8080 go to port 80 in the container. The SETMARK rules mark connections from the subnet itself and from host loopback so NAT works in the return direction too. That is why curl http://localhost:8080 worked.
nerdctl also fills in the files and hostname that ctr left alone.
nerdctl exec web sh -c 'hostname; cat /etc/resolv.conf; cat /etc/hosts'
e970ec8be4f0
nameserver 192.168.10.1
# <nerdctl>
127.0.0.1 localhost localhost.localdomain
::1 localhost localhost.localdomain
10.4.0.2 e970ec8be4f0 web
# </nerdctl>
The hostname is the short container ID, the DNS servers come from the host’s upstream resolver list, and /etc/hosts has an entry for the container itself. nerdctl rm cleans up the iptables rules when it removes the container.
Mount host directories and files
A bind mount of a host directory uses the same syntax as Docker, -v <host-path>:<container-path>.
img=docker.io/library/alpine:3.24
mkdir -p /srv/share
echo 'hello from host' > /srv/share/hello.txt
nerdctl run --rm -v /srv/share:/data $img sh -c 'cat /data/hello.txt; echo written in container > /data/from-container.txt'
cat /srv/share/from-container.txt
hello from host
written in container
Writes are visible on both sides. Add :ro to make the mount read-only.
nerdctl run --rm -v /srv/share:/data:ro $img sh -c 'echo x > /data/ro.txt'
sh: can't create /data/ro.txt: Read-only file system
Mount a single file in the same way. The equivalent in ctr uses --mount with explicit options.
mkdir -p /srv/lab
echo 'version=1' > /srv/lab/app.conf
nerdctl run --rm -v /srv/lab/app.conf:/config/app.conf $img sh -c 'ls -l /config; cat /config/app.conf'
ctr run --rm --mount type=bind,src=/srv/lab/app.conf,dst=/config/app.conf,options=rbind:ro $img m2 sh -c 'cat /config/app.conf; echo x >> /config/app.conf'
total 4
-rw-r--r-- 1 root root 10 Nov 10 12:26 app.conf
version=1
version=1
sh: can't create /config/app.conf: Read-only file system
Bind-mounting a file has a catch. Start a container and change the file on the host in two different ways. First write into the existing file. Then use sed -i, which, like many editors, writes a new file and replaces the old one.
id=$(nerdctl run -d -v /srv/share:/data -v /srv/lab/app.conf:/config/app.conf $img sleep 100000)
echo 'version=2' > /srv/lab/app.conf
echo 'new file' > /srv/share/new.txt
nerdctl exec $id sh -c 'cat /config/app.conf; ls /data; ls -i /config/app.conf'
ls -i /srv/lab/app.conf
sed -i 's/version=2/version=3/' /srv/lab/app.conf
cat /srv/lab/app.conf
ls -i /srv/lab/app.conf
nerdctl exec $id sh -c 'cat /config/app.conf; ls -i /config/app.conf'
pid=$(nerdctl inspect $id | jq -r '.[0].State.Pid')
grep -E 'app.conf' /proc/$pid/mountinfo
nerdctl rm -f $id > /dev/null
version=2
from-container.txt
hello.txt
new.txt
793490 /config/app.conf
793490 /srv/lab/app.conf
version=3
793492 /srv/lab/app.conf
version=2
793490 /config/app.conf
457 448 8:2 /srv/lab/app.conf//deleted /config/app.conf rw,relatime master:1 - ext4 /dev/sda2 rw
After the first write the container sees the new content. After sed -i, the host sees version=3 while the container still sees version=2. The bind mount references the original inode (793490). The replacement has a different inode (793492), and the mount table marks the old one as //deleted. A directory mount avoids this problem. Since it references the directory itself, new.txt shows up immediately.
Limit memory and CPU
Container processes run on the host kernel, which applies their cgroup limits. Let’s see what --memory and --cpus do.
Memory
Inside the container, a shell keeps doubling a string until something stops it. First, check what the container knows about its memory.
nerdctl run --rm --name m0 $img sh -c 'grep MemTotal /proc/meminfo; cat /sys/fs/cgroup/memory.max'
nerdctl run --name m1 --memory 128m $img sh -c 'grep MemTotal /proc/meminfo; cat /sys/fs/cgroup/memory.max; cat /sys/fs/cgroup/memory.swap.max; x=aaaaaaaaaaaaaaaa; while :; do x=$x$x; echo ${#x}; done'
echo "exit $?"
journalctl -k -o cat | grep 'Killed process'
nerdctl rm m1 > /dev/null
MemTotal: 7601584 kB
max
MemTotal: 7601584 kB
134217728
134217728
32
64
...
33554432
67108864
exit 137
Memory cgroup out of memory: Killed process 5326 (sh) total-vm:394876kB, anon-rss:97388kB, file-rss:1036kB, shmem-rss:0kB, UID:0 pgtables:508kB oom_score_adj:-998
/proc/meminfo reports the host’s full memory. A program sizing its buffers from MemTotal would get the wrong value for the container. The actual limit is in memory.max: 134217728 bytes, or 128 MiB. memory.swap.max shows that the container can use another 128 MiB of swap.
The kernel killed the process before it could report an allocation error. Exit status 137 is 128 plus 9, the number of SIGKILL. The kernel log names the group that exceeded the limit and the process it killed. This is the out-of-memory (OOM) killer at work.
CPU
Start four infinite loops in the container, each trying to use an entire core. From the host, measure how much CPU time the container’s cgroup receives over five seconds. cpu.stat records this time in microseconds.
for lim in "" "--cpus 1" "--cpus 0.5"; do
id=$(nerdctl run -d $lim $img sh -c 'for i in 1 2 3 4; do (while :; do :; done) & done; wait')
sleep 3
pid=$(nerdctl inspect $id | jq -r '.[0].State.Pid')
cg=/sys/fs/cgroup$(sed 's/^0:://' /proc/$pid/cgroup)
a=$(awk '/usage_usec/{print $2}' $cg/cpu.stat); sleep 5; b=$(awk '/usage_usec/{print $2}' $cg/cpu.stat)
echo "limit: ${lim:-none}; cores used: $(awk "BEGIN{printf \"%.2f\", ($b-$a)/5000000}")"
nerdctl rm -f $id > /dev/null
done
limit: none; cores used: 4.00
limit: --cpus 1; cores used: 1.00
limit: --cpus 0.5; cores used: 0.50
Without a limit, the four loops used all four cores. With --cpus 1 they shared one core’s worth of time, and with 0.5 they shared half a core’s worth.
Inspect the container specification
nerdctl records the limits in the container’s OCI JSON specification. runc applies them through the cgroup files.
id=$(nerdctl run -d --memory 128m --cpus 1 $img sleep 100000)
ctr containers info $id | jq '.Spec.linux.resources | {memory, cpu}'
pid=$(nerdctl inspect $id | jq -r '.[0].State.Pid')
cg=/sys/fs/cgroup$(sed 's/^0:://' /proc/$pid/cgroup)
echo $cg
cat $cg/memory.max $cg/cpu.max
nerdctl rm -f $id > /dev/null
{
"memory": {
"limit": 134217728,
"swap": 268435456
},
"cpu": {
"quota": 100000,
"period": 100000,
"realtimeRuntime": 0,
"realtimePeriod": 0
}
}
/sys/fs/cgroup/system.slice/nerdctl-5cb1d9684300a72c0c8bd9e28eb09ca1cc5c509a3778861290adf3d21e973f9b.scope
134217728
100000 100000
cpu.max allows 100,000 microseconds of CPU time every 100,000 microseconds, equivalent to one core. swap in the specification is 256 MiB because OCI counts memory and swap together. In cgroup v2, memory.swap.max counts only swap. In Part 5 we will create a cgroup and write these files ourselves.
Clean up
Remove the containers, images, and directories from this part. Each part of the series creates its own lab artifacts and removes them at the end.
nerdctl rm -f web
nerdctl rmi docker.io/library/nginx:1.30-alpine docker.io/library/alpine:3.24 > /dev/null
rm -rf /srv/share /srv/lab
nerdctl ps -a
nerdctl images
web
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
Keep the containerd service, runc, nerdctl, and the CNI plugins installed.
Run the installation as a script
install-containerd.sh downloads containerd, runc, the CNI plugins, and nerdctl, verifies their checksums, installs the files, writes the configuration, and starts the service. Set the versions and subnet through environment variables.
sudo CONTAINERD_VERSION=2.4.2 RUNC_VERSION=1.5.2 CNI_VERSION=1.10.0 NERDCTL_VERSION=2.4.2 SUBNET=172.30.0.0/16 GATEWAY=172.30.0.1 ./install-containerd.sh
The script was tested on a clean system running the same Ubuntu release as this article.
References
- Install containerd, runc, and the CNI plugins. containerd getting started guide
- See the reference implementation of the OCI runtime specification. runc
- Look up plugin commands, configuration, and the
.conflistformat. CNI specification - Look up the plugin options. CNI bridge plugin and CNI portmap plugin
- Find Docker-style commands for containerd. nerdctl
- See the
linux.resourcessection of the container specification. OCI Linux configuration - Look up Linux namespaces. namespaces(7)
- Look up
memory.max,memory.swap.max, andcpu.max. Control Group v2
Next, we go below containerd, write a container specification ourselves, and start the container with a single runc command.
Only registered users can leave a comment.
Sign in or register to leave a comment.