§2023-06-18
systemd-nspawn is like the chroot command, but it is a chroot on steroids.
systemd-nspawn may be used to run a command or OS in a light-weight namespace container. It is more powerful than chroot since it fully virtualizes the file system hierarchy, as well as the process tree, the various IPC subsystems and the host and domain name.
systemd-nspawn limits access to various kernel interfaces in the container to read-only, such as /sys, /proc/sys or /sys/fs/selinux. Network interfaces and the system clock may not be changed from within the container. Device nodes may not be created. The host system cannot be rebooted and kernel modules may not be loaded from within the container.
systemd-nspawn is a simpler tool to configure than LXC or Libvirt.
- Installation
- systemd-nspawn is part of and packaged with systemd.
- Example
- Create and boot a minimal Arch Linux container
試作機器: N2MnJaro, manjaro-arm-installer built image
-
First install arch-install-scripts.
$ sduo pacman -S arch-install-scripts
-
create format and mount boot root partitons
Device Boot Start End Sectors Size Id Type /dev/sda1 2048 1050623 1048576 512M 83 Linux /dev/sda2 1050624 15269887 14219264 6.8G 83 Linux sda ├─sda1 ext4 1.0 230de2ce-cf5d-44dd-a8ea-20405aa8b170 └─sda2 ext4 1.0 c13ac04d-38fe-4d72-9870-b070f1d4b4bd $ mkdir -p build/src && cd $_ $ mkdir root boot $ sudo mount /dev/sda2 root mount: (hint) your fstab has been modified, but systemd still uses the old version; use 'systemctl daemon-reload' to reload. $ sudo systemctl daemon-reload
- get pacstrap from arch distribution
- run
$ sudo pacstrap -K -c ~/build/src/root base ==> Creating install root at /home/alexlai/build/src/root gpg: /home/alexlai/build/src/root/etc/pacman.d/gnupg/trustdb.gpg: trustdb created gpg: no ultimately trusted keys found gpg: starting migration from earlier GnuPG versions gpg: porting secret keys from '/home/alexlai/build/src/root/etc/pacman.d/gnupg/secring.gpg' to gpg-agent gpg: migration succeeded ==> Generating pacman master key. This may take some time. gpg: Generating pacman keyring master key... gpg: directory '/home/alexlai/build/src/root/etc/pacman.d/gnupg/openpgp-revocs.d' created gpg: revocation certificate stored as '/home/alexlai/build/src/root/etc/pacman.d/gnupg/openpgp-revocs.d/D3F1F5A07BC2F9135CFB43E7926803162DD72F41.rev' gpg: Done ==> Updating trust database... gpg: marginals needed: 3 completes needed: 1 trust model: pgp gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u ==> Installing packages to /home/alexlai/build/src/root :: Synchronizing package databases... core 260.0 KiB 51.8 KiB/s 00:05 [###################################################################################################] 100% extra 2.3 MiB 438 KiB/s 00:05 [###################################################################################################] 100% community 6.7 MiB 1003 KiB/s 00:07 [###################################################################################################] 100% resolving dependencies... looking for conflicting packages... warning: dependency cycle detected: warning: archlinuxarm-keyring will be installed before its pacman dependency warning: dependency cycle detected: warning: manjaro-keyring will be installed before its pacman dependency Packages (126) acl-2.3.1-3 archlinux-keyring-20230504-1 archlinuxarm-keyring-20140119-2 argon2-20190702-5 attr-2.5.1-3 audit-3.1.1-1 bash-5.1.016-3 brotli-1.0.9-12 bzip2-1.0.8-5 ca-certificates-20220905-1 ca-certificates-mozilla-3.89.1-1 ca-certificates-utils-20220905-1 coreutils-9.3-1 cryptsetup-2.6.1-3 curl-8.1.0-1 db5.3-5.3.28-2 dbus-1.14.6-2 device-mapper-2.03.21-1 e2fsprogs-1.47.0-1 expat-2.5.0-1 file-5.44-3 filesystem-2023.01-1 findutils-4.9.0-3 gawk-5.2.2-1 gcc-libs-12.1.0-2.1 gdbm-1.23-2 gettext-0.21.1-5 glib2-2.76.2-1 glibc-2.35-5.1 gmp-6.2.1-2 gnupg-2.2.41-1 gnutls-3.8.0-1.1 gpgme-1.20.0-3 grep-3.11-1 gzip-1.12-2 hwdata-0.370-1 iana-etc-20230405-1 icu-72.1-2 iproute2-6.3.0-2 iptables-1:1.8.9-1 iputils-20221126-1 json-c-0.16-1 kbd-2.5.1-2 keyutils-1.6.3-2 kmod-30-3 krb5-1.20.1-1 less-1:633-1 libarchive-3.6.2-2 libassuan-2.5.5-2 libbpf-1.2.0-1 libcap-2.69-1 libcap-ng-0.8.3-2 libelf-0.189-1 libevent-2.1.12-4 libffi-3.4.4-1 libgcrypt-1.10.2-1 libgpg-error-1.47-1 libidn2-2.3.4-3.1 libksba-1.6.3-1 libldap-2.6.4-2 libmnl-1.0.5-1 libnetfilter_conntrack-1.0.9-1 libnfnetlink-1.0.2-1 libnftnl-1.2.5-1 libnghttp2-1.53.0-1 libnl-3.7.0-3 libnsl-2.0.0-3 libp11-kit-0.24.1-1 libpcap-1.10.4-1 libpsl-0.21.2-1 libsasl-2.1.28-4 libseccomp-2.5.4-2 libsecret-0.20.5-2 libssh2-1.10.0-3 libsysprof-capture-3.48.0-1 libtasn1-4.19.0-1 libtirpc-1.3.3-2 libunistring-1.1-2 libverto-0.3.2-4 libxcrypt-4.4.33-1 libxml2-2.10.4-4 licenses-20220125-2 linux-api-headers-6.3-1 lz4-1:1.9.4-1 manjaro-arm-keyring-20220210-1 manjaro-keyring-20221028-4 mpfr-4.2.0.p7-2 ncurses-6.4-1 nettle-3.9-1 npth-1.6-4 openssl-3.0.8-1 p11-kit-0.24.1-1 pacman-6.0.2-2 pacman-mirrors-4.23.2+3+g4148c3d-1 pam-1.5.3-1 pambase-20221020-1 pciutils-3.10.0-1 pcre2-10.42-2 perl-5.36.1-1 pinentry-1.2.1-1 popt-1.19-1 procps-ng-3.3.17-1 psmisc-23.6-1 python-3.11.3-1 python-certifi-2022.12.07-3 python-chardet-5.1.0-3 python-idna-3.4-3 python-npyscreen-4.10.5-8 python-requests-2.28.2-4 python-urllib3-1.26.15-1 readline-8.2.001-2 sed-4.9-3 shadow-4.13-2 sqlite-3.42.0-1 systemd-253.4-1 systemd-libs-253.4-1 systemd-sysvcompat-253.4-1 tar-1.34-2 tpm2-tss-4.0.1-1 tzdata-2023c-2 util-linux-2.38.1-4 util-linux-libs-2.38.1-4 xz-5.4.3-1 zlib-1:1.2.13-2 zstd-1.5.5-1 base-3-1 Total Download Size: 136.88 MiB Total Installed Size: 635.08 MiB :: Proceed with installation? [Y/n] ... (11/12) Warn about old perl modules perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LANGUAGE = (unset), LC_ALL = (unset), LANG = "en_US.UTF-8" are supported and installed on your system. perl: warning: Falling back to the standard locale ("C"). (12/12) Configuring pacman-mirrors ... ::WARNING https://repo.manjaro.org 'Connection: HTTPSConnectionPool(host='repo.manjaro.org', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0xffff9d742550>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))' ::WARNING https://wikipedia.org 'Connection: HTTPSConnectionPool(host='wikipedia.org', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0xffff9d742fd0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))' ::WARNING https://bitbucket.org 'Connection: HTTPSConnectionPool(host='bitbucket.org', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0xffff9d739550>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))' ::INFO Internet connection appears to be down ::INFO Mirror ranking is not available ::INFO Mirror list is generated using random method ::INFO Writing mirror list ::Brazil : https://manjaro.c3sl.ufpr.br/arm-stable ::United_States : https://mirror.clarkson.edu/manjaro/arm-stable ::Spain : http://ftp.caliu.cat/manjaro/arm-stable ::Austria : http://mirror.inode.at/manjaro/arm-stable ::South_Africa : http://mirror.is.co.za/mirrors/manjaro.org/arm-stable ::Italy : https://manjaro.mirror.garr.it/mirrors/manjaro/arm-stable ::Iran : https://repo.sadjad.ac.ir/manjaro/arm-stable ::Ecuador : https://mirror.espoch.edu.ec/manjaro/arm-stable ::Philippines : http://mirror.rise.ph/manjaro/arm-stable ::Indonesia : http://kambing.ui.ac.id/manjaro/arm-stable ::Germany : https://ftp.halifax.rwth-aachen.de/manjaro/arm-stable ::Colombia : http://mirror.upb.edu.co/manjaroarm-stable ::Chile : http://manjaro.dcc.uchile.cl/arm-stable ::Belgium : http://ftp.belnet.be/mirrors/manjaro/arm-stable ::Germany : https://mirror.netcologne.de/manjaro/arm-stable ::United_Kingdom : https://www.mirrorservice.org/sites/repo.manjaro.org/repos/arm ::Russia : http://mirror.truenetwork.ru/manjaro/arm-stable ::United_Kingdom : http://manjaro.mirrors.uk2.net/arm-stable ::France : http://kibo.remi.lu/arm-stable ::Germany : https://mirror.netzspielplatz.de/manjaro/packages/arm-stable ::United_States : https://mirror.math.princeton.edu/pub/manjaro/arm-stable ::Germany : https://repo.rhindon.net/manjaro/arm-stable ::Sweden : https://mirror.zetup.net/manjaro/arm-stable ::China : https://mirrors.ustc.edu.cn/manjaro/arm-stable ::Denmark : https://www.uex.dk/public/manjaro/arm-stable ::Germany : http://ftp.tu-chemnitz.de/pub/linux/manjaro/arm-stable ::United_States : https://mirrors.ocf.berkeley.edu/manjaro/arm-stable ::South_Africa : http://manjaro.mirror.ac.za/arm-stable ::Germany : https://manjaro.moson.eu/arm-stable ::Portugal : http://manjaro.barata.pt/arm-stable ::Brazil : http://linorg.usp.br/manjaro/arm-stable ::United_Kingdom : http://mirror.catn.com/pub/manjaro/arm-stable ::China : http://mirrors.tuna.tsinghua.edu.cn/manjaro/arm-stable ::Australia : http://manjaro.melbourneitmirror.net/arm-stable ::Singapore : https://download.nus.edu.sg/mirror/manjaro/arm-stable ::United_States : http://distro.ibiblio.org/manjaro/arm-stable ::Bulgaria : http://manjaro.telecoms.bg/arm-stable ::Bulgaria : https://mirrors.netix.net/manjaro/arm-stable ::Japan : http://ftp.tsukuba.wide.ad.jp/Linux/manjaro/arm-stable ::Belgium : https://manjaro.cu.be/arm-stable ::Germany : http://ftp.rz.tu-bs.de/pub/mirror/manjaro.org/repos/arm-stable ::Germany : https://mirror.philpot.de/manjaro/arm-stable ::China : https://mirrors.zju.edu.cn/manjaro/arm-stable ::Germany : http://mirror.ragenetwork.de/manjaro/arm-stable ::Hong_Kong : http://ftp.cuhk.edu.hk/pub/Linux/manjaro/arm-stable ::Turkey : http://ftp.linux.org.tr/manjaro/arm-stable ::United_States : http://mirror.dacentec.com/manjaro/arm-stable ::China : https://mirrors.sjtug.sjtu.edu.cn/manjaroarm-stable ::Belarus : http://mirror.datacenter.by/pub/mirrors/manjaro/arm-stable ::Sweden : https://ftp.lysator.liu.se/pub/manjaro/arm-stable ::Italy : https://ba.mirror.garr.it/mirrors/manjaro/arm-stable ::Netherlands : https://mirror.koddos.net/manjaro/arm-stable ::Netherlands : https://ftp.nluug.nl/pub/os/Linux/distr/manjaro/arm-stable ::Italy : https://ct.mirror.garr.it/mirrors/manjaro/arm-stable ::Taiwan : http://free.nchc.org.tw/manjaro/arm-stable ::Poland : https://mirror.tuchola-dc.pl/manjaro/arm-stable ::Czech : https://mirror.dkm.cz/manjaro/arm-stable ::China : https://mirrors.shu.edu.cn/manjaro/arm-stable ::Canada : https://osmirror.org/manjaro/arm-stable ::Brazil : http://mirror.ufam.edu.br/manjaro/arm-stable ::United_Kingdom : http://repo.manjaro.org.uk/arm-stable ::Indonesia : http://kartolo.sby.datautama.net.id/manjaro/arm-stable ::Netherlands : http://ftp.snt.utwente.nl/pub/linux/manjaro/arm-stable ::Poland : http://mirror.chmuri.net/manjaro/arm-stable ::Costa_Rica : https://mirrors.ucr.ac.cr/manjaro/arm-stable ::Greece : https://ftp.cc.uoc.gr/mirrors/linux/manjaro/arm-stable ::Romania : http://mirrors.serverhost.ro/manjaro/packages/arm-stable ::Japan : http://ftp.riken.jp/Linux/manjaro/arm-stable ::Bulgaria : https://manjaro.ipacct.com/manjaro/arm-stable ::Ecuador : https://mirror.cedia.org.ec/manjaro/arm-stable ::Brazil : http://pet.inf.ufsc.br/mirrors/manjarolinux/arm-stable ::Denmark : https://mirrors.dotsrc.org/manjaro/arm-stable ::China : https://mirrors.shuosc.org/manjaro/arm-stable ::Bangladesh : http://mirror.xeonbd.com/manjaro/arm-stable ::Hungary : http://mirror.infotronik.hu/mirrors/pub/manjaro/arm-stable ::France : http://ftp.free.org/mirrors/repo.manjaro.org/repos/arm-stable ::Australia : http://mirror.ventraip.net.au/Manjaro/arm-stable ::Russia : https://mirror.yandex.ru/mirrors/manjaro/arm-stable ::INFO Mirror list generated and saved to: /etc/pacman.d/mirrorlist hint: use `pacman-mirrors` to generate and update your pacman mirrorlist.
- -K Initialize an empty pacman keyring in the target (implies '-G')
- -c Use the package cache on the host, rather than the target
Tip: The base package does not depend on the linux kernel package and is container-ready.
- Once your installation is finished, chroot into the container, and set a root password:
```bash
# systemd-nspawn -D /home/alexlai/build/src/root
Spawning container root on /home/alexlai/build/src/root.
Press Ctrl-] three times within 1s to kill container.
# passwd
New password:
Retype new password:
passwd: password updated successfully
[root@root ~]# useradd -m -G wheel -u 1026 alexlai
[root@root ~]# passwd alexlai
New password:
Retype new password:
passwd: password updated successfully
[root@root ~]# logout
Container root exited successfully.
```
- Finally, boot into the container:
```bash
# systemd-nspawn -b -D /home/alexlai/build/src/root/
Spawning container root on /home/alexlai/build/src/root.
Press Ctrl-] three times within 1s to kill container.
systemd 253.4-1-arch running in system mode (+PAM +AUDIT -SELINUX -APPARMOR -IMA +SMACK +SECCOMP +GCRYPT +GNUTLS +OPENSSL +ACL +BLKID +CURL +ELFUTILS +FIDO2 +IDN2 -IDN +IPTC +KMOD +LIBCRYPTSETUP +LIBFDISK +PCRE2 -PWQUALITY +P11KIT -QRENCODE +TPM2 +BZIP2 +LZ4 +XZ +ZLIB +ZSTD +BPF_FRAMEWORK +XKBCOMMON +UTMP -SYSVINIT default-hierarchy=unified)
Detected virtualization systemd-nspawn.
Detected architecture arm64.
Welcome to Manjaro ARM!
bpf-lsm: BPF LSM hook not enabled in the kernel, BPF LSM not supported
Queued start job for default target Graphical Interface.
[ OK ] Created slice Slice /system/getty.
[ OK ] Created slice Slice /system/modprobe.
[ OK ] Created slice User and Session Slice.
[ OK ] Started Dispatch Password Requests to Console Directory Watch.
[ OK ] Started Forward Password Requests to Wall Directory Watch.
[ OK ] Reached target Local Encrypted Volumes.
[ OK ] Reached target Local Integrity Protected Volumes.
[ OK ] Reached target Path Units.
[ OK ] Reached target Remote File Systems.
[ OK ] Reached target Slice Units.
[ OK ] Reached target Swaps.
[ OK ] Reached target Local Verity Protected Volumes.
[ OK ] Listening on Device-mapper event daemon FIFOs.
[ OK ] Listening on Process Core Dump Socket.
[ OK ] Listening on Journal Socket (/dev/log).
[ OK ] Listening on Journal Socket.
Mounting Huge Pages File System...
Mounting FUSE Control File System...
Starting Journal Service...
Starting Remount Root and Kernel File Systems...
[ OK ] Mounted Huge Pages File System.
[ OK ] Mounted FUSE Control File System.
[ OK ] Finished Remount Root and Kernel File Systems.
Starting Create System Users...
[ OK ] Started Journal Service.
Starting Flush Journal to Persistent Storage...
[ OK ] Finished Create System Users.
Starting Create Static Device Nodes in /dev...
[ OK ] Finished Create Static Device Nodes in /dev.
[ OK ] Reached target Preparation for Local File Systems.
[ OK ] Reached target Local File Systems.
Starting Rebuild Dynamic Linker Cache...
[ OK ] Finished Flush Journal to Persistent Storage.
Starting Create Volatile Files and Directories...
[ OK ] Finished Rebuild Dynamic Linker Cache.
[ OK ] Finished Create Volatile Files and Directories.
Starting Rebuild Journal Catalog...
Starting Record System Boot/Shutdown in UTMP...
[ OK ] Finished Record System Boot/Shutdown in UTMP.
[ OK ] Finished Rebuild Journal Catalog.
Starting Update is Completed...
[ OK ] Finished Update is Completed.
[ OK ] Reached target System Initialization.
[ OK ] Started Refresh existing PGP keys of archlinux-keyring regularly.
[ OK ] Started Daily verification of password and group files.
[ OK ] Started Daily Cleanup of Temporary Directories.
[ OK ] Reached target Timer Units.
[ OK ] Listening on D-Bus System Message Bus Socket.
[ OK ] Reached target Socket Units.
[ OK ] Reached target Basic System.
Starting D-Bus System Message Bus...
Starting User Login Management...
Starting Permit User Sessions...
[ OK ] Started D-Bus System Message Bus.
[ OK ] Finished Permit User Sessions.
[ OK ] Started Console Getty.
[ OK ] Reached target Login Prompts.
[ OK ] Started User Login Management.
[ OK ] Reached target Multi-User System.
[ OK ] Reached target Graphical Interface.
Manjaro Linux 6.3.7-1-MANJARO-ARM (pts/0)
root login: alexlai
Password:
Welcome to Manjaro ARM
~~Website: https://manjaro.org
~~Forum: https://forum.manjaro.org/c/arm
~~Matrix: #manjaro-arm-public:matrix.org
[alexlai@root ~]$ id
uid=1026(alexlai) gid=1026(alexlai) groups=1026(alexlai),998(wheel)
[alexlai@root ~]$ ip ad
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:1e:06:42:c6:87 brd ff:ff:ff:ff:ff:ff
altname end0
inet 192.168.48.5/24 brd 192.168.48.255 scope global dynamic noprefixroute eth0
valid_lft 96436sec preferred_lft 74836sec
inet6 fe80::d60:ac77:d1c1:2c01/64 scope link
valid_lft forever preferred_lft forever
```
- Examples
- Create and boot a minimal Arch Linux container
試作機器: hc4Bullseye.yushei.net(Debian 11 bullseye)
- First install arch-install-scripts.
$ sudo apt install arch-install-scripts alexlai@hc4Bullseye:~$ dpkg -L arch-install-scripts /. /usr /usr/bin /usr/bin/arch-chroot /usr/bin/genfstab /usr/share /usr/share/bash-completion /usr/share/bash-completion/completions /usr/share/bash-completion/completions/arch-chroot /usr/share/bash-completion/completions/genfstab /usr/share/doc /usr/share/doc/arch-install-scripts /usr/share/doc/arch-install-scripts/README.md /usr/share/doc/arch-install-scripts/changelog.Debian.gz /usr/share/doc/arch-install-scripts/copyright /usr/share/man /usr/share/man/man8 /usr/share/man/man8/arch-chroot.8.gz /usr/share/man/man8/genfstab.8.gz /usr/share/zsh /usr/share/zsh/site-functions /usr/share/zsh/site-functions/_archinstallscripts
- we will use ~/MyContainer
$ mkdir ~/MyContainer && cd $_
- get pacstrap from arch distribution
- run
alexlai@hc4Bullseye:~/build/src$ sudo ./pacstrap -K -c ~/MyContainer base [sudo] password for alexlai: ==> Creating install root at /home/alexlai/MyContainer ./pacstrap: line 479: pacman-key: command not found ==> Installing packages to /home/alexlai/MyContainer unshare: failed to execute pacman: No such file or directory ==> ERROR: Failed to install packages to new root