Example 1. Download a Fedora image and start a shell in it
# machinectl pull-raw --verify=no \
https://download.fedoraproject.org/pub/fedora/linux/releases/34/Cloud/x86_64/images/Fedora-Cloud-Base-34-1.2.x86_64.raw.xz \
Fedora-Cloud-Base-34-1.2.x86-64
# systemd-nspawn -M Fedora-Cloud-Base-34-1.2.x86-64
This downloads an image using machinectl(1) and opens a shell in
it.
Example 2. Build and boot a minimal Fedora distribution in a
container
# dnf -y --releasever=34 --installroot=/var/lib/machines/f34 \
--disablerepo='*' --enablerepo=fedora --enablerepo=updates install \
systemd passwd dnf fedora-release vim-minimal glibc-minimal-langpack
# systemd-nspawn -bD /var/lib/machines/f34
This installs a minimal Fedora distribution into the directory
/var/lib/machines/f34 and then boots that OS in a namespace
container. Because the installation is located underneath the
standard /var/lib/machines/ directory, it is also possible to
start the machine using systemd-nspawn -M f34
.
Example 3. Spawn a shell in a container of a minimal Debian
unstable distribution
# debootstrap unstable ~/debian-tree/
# systemd-nspawn -D ~/debian-tree/
This installs a minimal Debian unstable distribution into the
directory ~/debian-tree/ and then spawns a shell from this image
in a namespace container.
debootstrap
supports Debian
[7], Ubuntu
[8], and Tanglu
[9] out of
the box, so the same command can be used to install any of those.
For other distributions from the Debian family, a mirror has to
be specified, see debootstrap
(8).
Example 4. Boot a minimal Arch Linux distribution in a container
# pacstrap -c ~/arch-tree/ base
# systemd-nspawn -bD ~/arch-tree/
This installs a minimal Arch Linux distribution into the
directory ~/arch-tree/ and then boots an OS in a namespace
container in it.
Example 5. Install the OpenSUSE Tumbleweed rolling distribution
# zypper --root=/var/lib/machines/tumbleweed ar -c \
https://download.opensuse.org/tumbleweed/repo/oss tumbleweed
# zypper --root=/var/lib/machines/tumbleweed refresh
# zypper --root=/var/lib/machines/tumbleweed install --no-recommends \
systemd shadow zypper openSUSE-release vim
# systemd-nspawn -M tumbleweed passwd root
# systemd-nspawn -M tumbleweed -b
Example 6. Boot into an ephemeral snapshot of the host system
# systemd-nspawn -D / -xb
This runs a copy of the host system in a snapshot which is
removed immediately when the container exits. All file system
changes made during runtime will be lost on shutdown, hence.
Example 7. Run a container with SELinux sandbox security contexts
# chcon system_u:object_r:svirt_sandbox_file_t:s0:c0,c1 -R /srv/container
# systemd-nspawn -L system_u:object_r:svirt_sandbox_file_t:s0:c0,c1 \
-Z system_u:system_r:svirt_lxc_net_t:s0:c0,c1 -D /srv/container /bin/sh
Example 8. Run a container with an OSTree deployment
# systemd-nspawn -b -i ~/image.raw \
--pivot-root=/ostree/deploy/$OS/deploy/$CHECKSUM:/sysroot \
--bind=+/sysroot/ostree/deploy/$OS/var:/var