Skip to content

systemd nspawn

Daniel Ellison edited this page Nov 19, 2018 · 11 revisions

It's quite easy to set up a standard systemd-nspawn container. On an Arch-based distribution you need the install scripts first:

$ sudo pacman --noconfirm -S arch-install-scripts

Once these are in place, you can issue the following commands, providing a container name for <name>:

$ sudo su
# export NAME='/var/lib/machines/<name>'
# mkdir -p $NAME
# pacstrap -i -c $NAME base --ignore linux
# systemd-nspawn -b -D $NAME

This will boot the container as if it's an actual machine. You'll be left at a login prompt, at which point you log in as root with no password. Of course, the first things to do would be to create a new non-root user and disable root login. You'll need sudo installed to give elevated access to the new user.

# pacman --noconfirm -S sudo
# useradd -c "Regular User" -d /home/user -m -s /bin/bash user
# echo "%user ALL=(ALL:ALL) ALL" > /etc/sudoers.d/user
# chmod 440 /etc/sudoers.d/user
# passwd user
# passwd --lock root
# reboot

Now you can log in as user and only elevate your privileges when necessary. To exit from this container you can either hold down the ctrl key and press ] three times in succession or you can execute the following command:

$ sudo poweroff

Both will shut down the container.

Using an nspawn container like this allows you to install any software you like without polluting your base system. When you don't want to use the container anymore, just issue sudo rm -rf $NAME and it's all gone. This is the basis of what I want to do with graphical software as well. With the proper sharing of resources you can keep your base system clean and contain any system changes to a container.

Clone this wiki locally