systemd-nspawn: Linux Containers

This is a tutorial to use systemd-nspawn (which I use because I haven’t understood Docker and this seems cooler xD).

Linux in a Container

Linux containers isolate applications from the host system they run on. More accurately

Linux containers are technologies that allow you to package and isolate applications with their runtime environment - all of the files necessary to run.

Thus, this enables us to run applications in their own environment to make testing and debugging easy.

Setting up the basic container

The first step is to make a directory. For brevity I’m calling my container foo. You can call it anything you want.

$ mkdir foo

NOTE: Please make sure that this directory has the symbolic permissions of 755 or else you will be unable to login as root in the container.

Now we not to strap an entire Linux root file system into this directory. This can be done using various tools. Since my host system is Arch Linux I am going to use pacstrap. Debian based distributions use debootstrap. Other distributions have similar bootstrapping tools.

$ sudo pacstrap -i -c -d /path/to/foo base base-devel

To start the container use systemd-nspawn which comes packaged with systemd

$ sudo systemd-nspawn -b -D /path/to/foo

This is starts the container with the same network interfaces as the host system. the -b flag tells systemd-nspawn to boot the container and the -D flag tells it that the next argument is a directory of the root filesystem.

This is sufficient for most cases. But in case you want to be able to create a virtual ethernet interface to the host system, run

$ sudo systemd-nspawn -b -D /path/to/foo -n

The -n switch creates a virtual ethernet interface veth between the host and container. This can be verified with your network client (usually networkctl, DHCP or connman).

Now setup your host system network to have IP forwarding (/etc/systemd/network/ the man page requires it:

Configures IP forwarding for the network interface. I enable incoming packets on the network interface will be forwarded to other interfaces according to the routing table.

To check IP forwarding

$ cat /proc/sys/net/ipv4/ip_forward

In case you are using a wireless network interface, a wireless interface is required (/etc/wpa_supplicant/wpa_supplicant-wlp***.conf) where the ‘*’s represent the unique characters in the name of your wireless interface.

Similarly setup the container network interface with the hostname and ip forwarding enabled.

Now the container is setup and running.

You can now do a lot from within the container. You can run specific applications, you can test and/or debug your applications, you can test your architecture on other architectures and with different build parameters, you can run a GUI app from the container like Steam. There is a whole wide world of opputunities…

Moriturus te Saluto!!