We will use systemd-nspawn to create a container that will use a fully isolated environment. This environment will use a virtualized filesystem and process hierarchy. It will allow us to install Linux-based operating systems on our host. We can change to our container to compile packages or to launch a virtual OS image.
Create a new container
The containers will be mounted under /var/lib/machines on our host and we will use logical volumes to store their data.
lvcreate -L 2G -n c.lab vg0 Logical volume "c.lab" created mkfs.ext4 -L "lab1" /dev/mapper/vg0-c.lab mkdir /var/lib/machines/lab mount /dev/mapper/vg0-c.lab /var/lib/machines/lab
Install an image
While we can use various Linux distribution specific installers or filesystem archives, we will use debootstrap to install our OS image.
debootstrap --arch=amd64 sid /var/lib/machines/lab http://ftp.de.debian.org/debian/ I: Retrieving InRelease I: Checking Release signature I: Valid Release signature (key id 16E90B3FDF65EDE3AA7F323C04EE7237B7D453EC) I: Retrieving Packages I: Validating Packages I: Resolving dependencies of required packages...
Change to the image
Change into our virtual container and name the machine lab1 internally:
systemd-nspawn -M lab1 -D /var/lib/machines/lab Spawning container lab1 on /var/lib/machines/lab. Press ^] three times within 1s to kill container. root@lab1:~#
We will change our hostname to lab1 and set a root password:
vi /etc/hostname passwd root Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully
After exiting our container we can now boot it.
Boot container
Launch container:
systemd-nspawn -b -M lab1 -D /var/lib/machines/lab Debian GNU/Linux buster/sid lab1 console lab1 login:
Manage containers
machinectl MACHINE CLASS SERVICE OS VERSION ADDRESSES lab1 container systemd-nspawn debian - - 1 machines listed.
machinectl status lab1
Reboot container:
machinectl reboot lab1
Stop container:
machinectl poweroff lab1
Control resources
We can limit the resources the container is able to utilize. The --runtime
parameter indicates a non-persistent change.
systemctl set-property --runtime machine-lab1.scope CPUShares=512 MemoryLimit=500M
systemctl status machine-lab1.scope ● machine-lab1.scope - Container lab1 Loaded: loaded (/run/systemd/transient/machine-lab1.scope; transient; vendor preset: enabled) Transient: yes Drop-In: /run/systemd/transient/machine-lab1.scope.d └─50-CPUShares.conf, 50-MemoryLimit.conf Active: active (running) since Sun 2018-07-08 15:13:13 CEST; 7min ago Tasks: 10 (limit: 16384) Memory: 26.2M (limit: 500.0M) CPU: 249ms
Display values:
systemctl show -p CPUShares machine-lab1.scope CPUShares=512
Revert resource controls:
systemctl revert machine-lab1.scope
Display Control Groups:
systemd-cgls