Post

Systemd containers with systemd-nspawn and debootstrap

Systemd containers with systemd-nspawn and debootstrap

Exploring Linux features is exciting, but it can be risky! I sometimes break my system while testing packages. To mitigate this, I discovered systemd-nspawn with debootstrap. It’s a lightweight container that works well for isolated testing.

In this guide, Debian/Ubuntu users will learn how to get systemd-nspawn up and running in no time.

Installing the pakcages

First things first, we need to install two packages: systemd-container and debootstrap:

1
sudo apt install systemd-container debootstrap

debootstrap lets you spin up a lightweight Debian/Ubuntu right on your host, and systemd-container utilities such as systemd-nspawn and machinectl manage the OS in a lightweight container.

Creating a virtual machine

Let’s generate a minimal Debian image called debian-testing with the following command:

1
2
# `bookworm` is latest debian code name
sudo debootstrap --include=systemd,dbus bookworm /var/lib/machines/debian-bookworm

To install minimal Ubuntu image, run:

1
2
# `jammy` is latest Ubuntu LTS codename.
sudo debootstrap --include=systemd,dbus --arch amd64 jammy /var/lib/machines/ubuntu-jammy  http://archive.ubuntu.com/ubuntu

To verify successful installation, run machinectl list-images. Look for debian-testing in the output.

1
2
3
4
5
6
 $ machinectl list-images
NAME            TYPE      RO USAGE CREATED                     MODIFIED
debian-bookworm directory no       Sun 2024-09-22 22:34:02 IST -
ubuntu-jammy    directory no       Sun 2024-09-22 21:53:45 IST -

2 images listed.

Logging into virtual machine

Use the following command to start the debian-bookworm container.

1
sudo systemd-nspawn -D /var/lib/machines/debian-bookworm # or ubuntu-jammy

Since you’re now inside your virtual machine, let’s set a password for the root user. This will come in handy when you want to manage the container using machinectl.

To swiftly terminate the container, press the Ctrl+] ky combination three times in quick succession while inside the container.

Runnin a graphical application in container

To run graphical apps like Chromium within the container, we need to set up display sharing. First, gracefully shut down the container. Then use this command to establish the container.

1
xhost local:; sudo systemd-nspawn -E DISPLAY="$DISPLAY" -D /var/lib/machines/debian-bookworm

Now that you’re logged in, it’s time to fire up Chromium! Just type the following commands to install and open it.

1
2
3
apt update
apt install Chromium
chromium --no-sandbox

References

This post is licensed under CC BY 4.0 by the author.