How to Use systemd-nspawn for Lightweight Linux Containers

Are you tired of cluttering your OS with unnecessary dependencies and dev tools for side projects that you might only use once? Do you want a simple way to keep all your project assets together? If so, you should try using systemd-nspawn to create lightweight Linux containers for your projects.

First, create a minimal Debian install using the debootstrap command:

sudo debootstrap stable `pwd`/os/

or (in my particular use case, I'm working with Debian unstable)

sudo debootstrap unstable `pwd`/os/

This will create a container that is only 240 megabytes in size.

Next, start the container using the following command:

sudo systemd-nspawn -D `pwd`/os -M MACHINENAME

Once the container is started, you can set up an account by running the following commands:

# set up account 
useradd -m user
passwd user

To set up software, run the following commands:

# this may be necessary on debian stable
apt install ca-certificates 
# set up software 
apt update
apt install nano vim curl # etc

With these simple steps, you can easily create lightweight Linux containers for your development and experimentation projects using systemd-nspawn.