How to Use systemd-nspawn Containers on Linux
A complete walkthrough creating and running a lightweight systemd-nspawn container — useful for isolated testing environments without the overhead of a full container runtime.
systemd-nspawn provides namespace-based container isolation built directly into systemd — using the same namespace primitives that underlie Docker and Podman, without needing a separate container runtime installed.
Step 1: create a root filesystem for the container
sudo dnf --releasever=39 --installroot=/var/lib/machines/mycontainer install systemd passwd dnf fedora-release vim-minimal -y
Or, on Debian-based systems:
sudo debootstrap stable /var/lib/machines/mycontainer http://deb.debian.org/debian
Either produces a minimal, bootable root filesystem in the standard /var/lib/machines/ location machinectl expects.
Step 2: boot the container
sudo systemd-nspawn -D /var/lib/machines/mycontainer -b
-b boots the container’s own init system (systemd) rather than just running a single command inside it — the container behaves like a lightweight, independently-booting system.
Step 3: manage it with machinectl instead of raw nspawn commands
sudo machinectl start mycontainer
sudo machinectl shell mycontainer
sudo machinectl stop mycontainer
machinectl is the higher-level tool for managing nspawn containers as persistent, named machines — closer to docker start/exec/stop in spirit.
Step 4: list running containers
machinectl list
Step 5: set resource limits via systemd’s own resource control
systemctl set-property machine-mycontainer.scope MemoryMax=512M CPUQuota=50%
Because nspawn containers run as systemd scopes, the same resource-control mechanisms covered in cgroups apply directly — no separate resource-limiting subsystem needed.
Step 6: share a directory between host and container
sudo systemd-nspawn -D /var/lib/machines/mycontainer --bind=/host/data:/data -b
Step 7: enable the container to start automatically at boot
sudo machinectl enable mycontainer
Step 8: remove a container you no longer need
sudo machinectl remove mycontainer
Why nspawn is worth knowing alongside Docker/Podman, not instead of them
nspawn containers boot a full init system and behave much more like lightweight VMs than application containers — genuinely useful for testing a full distribution environment, building packages in isolation, or running a legacy service that expects a real init system, scenarios where Docker’s single-process-per-container model is a worse fit. It’s a different tool for a different job, not a competing choice for the container-orchestration workloads Docker and Podman are built around.