Mastering systemd-nspawn: Lightweight Linux Containers Without Docker

Linux tutorial - IT technology blog
Linux tutorial - IT technology blog

Real-World Problem: The 2 AM PagerDuty Crash on a 2GB Node

My phone vibrated violently on the nightstand at 2:18 AM. PagerDuty fired four concurrent alerts across our European staging nodes: background queue workers had frozen solid. I hopped onto my laptop, opened a terminal, and SSH’d into the primary worker node. Running docker ps hung completely without returning a byte. A quick look at dmesg exposed the carnage:

kernel: [ 4812.910214] Out of memory: Kill process 1248 (dockerd) score 412 or sacrifice child
kernel: [ 4812.910892] Killed process 1248 (dockerd) total-vm:1894212kB, anon-rss:512400kB

The Linux kernel’s OOM killer had nuked the Docker daemon. Between dockerd, containerd, network bridge helpers, and two zombie shim processes, the container runtime itself chewed up over 520MB of our meager 2GB RAM. Our actual Python ingestion script needed barely 90MB. Restarting Docker brought the queue back online, but the math was broken. We were burning over 25% of our system budget babysitting the tool that ran the code.

Root Cause: Daemon Tax and Process Nesting

Docker revolutionized local testing and image builds. However, on small production servers or edge boxes running fixed services, its runtime architecture levies a heavy operational tax:

  • Idle memory overhead: Both dockerd and containerd run continuously as root daemons. They parse REST requests, maintain JSON state, and manage internal event buses. This idle overhead typically consumes between 300MB and 700MB of resident RAM before running a single payload.
  • Deep process chains: Each active container spawns a deep parent-child tree: systemd → dockerd → containerd → containerd-shim → runc → your application. Every hop adds context switches, file descriptors, and memory overhead.
  • Fragile control sockets: If the Docker socket hangs or an image prune deadlocks on an orphan layer, every isolated service on that host turns into an unmanageable black box.

Sitting in the dark at 3:00 AM, the answer was staring right at me from ps aux. We did not need an embedded image registry, an overlay filesystem manager, or a REST API server. We just needed process isolation, cgroup caps, and standard networking. Linux already has a battle-tested service supervisor that does this out of the box: systemd.

Comparing Options: chroot vs. Docker vs. systemd-nspawn

Choosing an isolation boundary on Linux comes down to trading control overhead against namespace separation:

Capability Classic chroot Docker / containerd systemd-nspawn
Namespace Isolation Filesystem only Full (PID, Mount, IPC, Net, User, UTS) Full (PID, Mount, IPC, Net, User, UTS)
Resource Limiting (cgroups v2) None Managed through Docker API Native systemd slice directives
Daemon Footprint Zero Heavy (~300MB to 600MB idle RAM) Zero (Kernel executes processes directly)
Runtime Memory Cost Zero High (~30MB to 50MB per container shim) Negligible (~12MB to 15MB kernel structs)
Process Supervision External shell wrappers Docker daemon restart policies Native systemd unit lifecycles

While chroot leaves process tables and network interfaces completely shared, Docker provides solid security boundaries at the expense of runtime bloat. That is where systemd-nspawn steps in. It configures the exact same Linux kernel namespaces and control groups as Docker, but without any daemon sitting between the host and your application.

Step-by-Step: Production Containers with systemd-nspawn

We migrated our background ingest workers on an Ubuntu 22.04 LTS host with 4GB of RAM. Memory consumption plummeted immediately, dropping from 680MB to 95MB total footprint. Here is how to configure it from scratch in under fifteen minutes.

Step 1: Install the Tooling

Install the systemd container package and debootstrap on Debian or Ubuntu. The latter lets you pull down a bare-bones base OS directory:

sudo apt-get update
sudo apt-get install -y systemd-container debootstrap

Step 2: Bootstrap the Root Filesystem

Next, place the rootfs inside /var/lib/machines/. Systemd treats this directory as the standard path for container images. Download a clean Debian Bookworm environment:

sudo mkdir -p /var/lib/machines/app-worker
sudo debootstrap --include=systemd,dbus,curl,python3-minimal bookworm /var/lib/machines/app-worker http://deb.debian.org/debian

Step 3: Access the Environment and Set Passwords

Open a chroot-like interactive shell inside your new machine directory to configure initial credentials:

sudo systemd-nspawn -D /var/lib/machines/app-worker

Set a root password and verify that the base environment functions. Once you finish, type exit or press Ctrl+] three times within one second to detach back to the host shell:

# Inside container environment
passwd
exit

Step 4: Boot into an Isolated Namespace with Private Networking

To boot the container as an independent instance with its own PID 1 init tree and virtual network pair, pass the -b and -n flags:

sudo systemd-nspawn -b -n -D /var/lib/machines/app-worker

You will see standard systemd boot logs cascade across the terminal. Log in using the root credentials you set earlier. The guest OS now runs cleanly isolated from all host processes.

Step 5: Control the Container with machinectl

Forget raw command wrappers in day-to-day operations. The built-in machinectl utility provides clean management for running containers:

# List active machines and inspect their status
machinectl list

# Open a login shell inside the container
machinectl shell app-worker

# Inspect memory usage, IP addresses, and the process tree
machinectl status app-worker

# Gracefully shut down the guest OS
sudo machinectl poweroff app-worker

Step 6: Configure Autostart with Native Systemd Units

Integrating nspawn containers into production boot flows requires zero extra scripts. Systemd ships with a parameterised service template ready out of the box:

# Enable the service on host startup
sudo systemctl enable [email protected]

# Start the container in the background
sudo systemctl start [email protected]

# Check service health and logs
systemctl status [email protected]

Step 7: Enforce Hardware Limits

A rogue container process should never crash your host. Apply cgroup limits directly to the container unit by opening an override file:

sudo systemctl edit [email protected]

Paste the directives below into the editor. This clamps the container to a strict 1GB memory cap and limits CPU usage to half a core:

[Service]
MemoryMax=1G
CPUQuota=50%

Save and exit the editor. Then apply the changes:

sudo systemctl restart [email protected]

Our staging nodes have operated continuously for eight months without a single OOM event. Idle memory hovers at 48MB per container, and log retrieval through journalctl -u systemd-nspawn@app-worker is instant.

Share: