table of contents
SYSTEMD-NSPAWN(1) | systemd-nspawn | SYSTEMD-NSPAWN(1) |
NAME¶
systemd-nspawn - Spawn a command or OS in a light-weight container
SYNOPSIS¶
systemd-nspawn [OPTIONS...] [COMMAND [ARGS...]]
systemd-nspawn --boot [OPTIONS...] [ARGS...]
DESCRIPTION¶
systemd-nspawn may be used to run a command or OS in a light-weight namespace container. In many ways it is similar to chroot(1), but more powerful 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 may be invoked on any directory tree containing an operating system tree, using the --directory= command line option. By using the --machine= option an OS tree is automatically searched for in a couple of locations, most importantly in /var/lib/machines/, the suggested directory to place OS container images installed on the system.
In contrast to chroot(1) systemd-nspawn may be used to boot full Linux-based operating systems in a container.
systemd-nspawn limits access to various kernel interfaces in the container to read-only, such as /sys/, /proc/sys/ or /sys/fs/selinux/. The host's 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.
Use a tool like dnf(8), debootstrap(8), or pacman(8) to set up an OS directory tree suitable as file system hierarchy for systemd-nspawn containers. See the Examples section below for details on suitable invocation of these commands.
As a safety check systemd-nspawn will verify the existence of /usr/lib/os-release or /etc/os-release in the container tree before booting a container (see os-release(5)). It might be necessary to add this file to the container tree manually if the OS of the container is too old to contain this file out-of-the-box.
systemd-nspawn may be invoked directly from the interactive command line or run as system service in the background. In this mode each container instance runs as its own service instance; a default template unit file systemd-nspawn@.service is provided to make this easy, taking the container name as instance identifier. Note that different default options apply when systemd-nspawn is invoked by the template unit file than interactively on the command line. Most importantly the template unit file makes use of the --boot option which is not the default in case systemd-nspawn is invoked from the interactive command line. Further differences with the defaults are documented along with the various supported options below.
The machinectl(1) tool may be used to execute a number of operations on containers. In particular it provides easy-to-use commands to run containers as system services using the systemd-nspawn@.service template unit file.
Along with each container a settings file with the .nspawn suffix may exist, containing additional settings to apply when running the container. See systemd.nspawn(5) for details. Settings files override the default options used by the systemd-nspawn@.service template unit file, making it usually unnecessary to alter this template file directly.
Note that systemd-nspawn will mount file systems private to the container to /dev/, /run/ and similar. These will not be visible outside of the container, and their contents will be lost when the container exits.
Note that running two systemd-nspawn containers from the same directory tree will not make processes in them see each other. The PID namespace separation of the two containers is complete and the containers will share very few runtime objects except for the underlying file system. Rather use machinectl(1)'s login or shell commands to request an additional login session in a running container.
systemd-nspawn implements the Container Interface[1] specification.
While running, containers invoked with systemd-nspawn are registered with the systemd-machined(8) service that keeps track of running containers, and provides programming interfaces to interact with them.
UNPRIVILEGED OPERATION¶
systemd-nspawn may be invoked with or without privileges. The full functionality is currently only available when invoked with privileges. When invoked without privileges, various limitations apply, including, but not limited to:
When running in unprivileged mode, some needed functionality is provided via systemd-mountfsd.service(8) and systemd-nsresourced.service(8)
OPTIONS¶
If option --boot is specified, the arguments are used as arguments for the init program. Otherwise, COMMAND specifies the program to launch in the container, and the remaining arguments are used as arguments for this program. If --boot is not used and no arguments are specified, a shell is launched in the container.
The following options are understood:
-q, --quiet
Added in version 209.
--settings=MODE
If enabled (the default), a settings file named after the machine (as specified with the --machine= setting, or derived from the directory or image file name) with the suffix .nspawn is searched in /etc/systemd/nspawn/ and /run/systemd/nspawn/. If it is found there, its settings are read and used. If it is not found there, it is subsequently searched in the same directory as the image file or in the immediate parent of the root directory of the container. In this case, if the file is found, its settings will be also read and used, but potentially unsafe settings are ignored. Note that in both these cases, settings on the command line take precedence over the corresponding settings from loaded .nspawn files, if both are specified. Unsafe settings are considered all settings that elevate the container's privileges or grant access to additional resources such as files or directories of the host. For details about the format and contents of .nspawn files, consult systemd.nspawn(5).
If this option is set to override, the file is searched, read and used the same way, however, the order of precedence is reversed: settings read from the .nspawn file will take precedence over the corresponding command line options, if both are specified.
If this option is set to trusted, the file is searched, read and used the same way, but regardless of being found in /etc/systemd/nspawn/, /run/systemd/nspawn/ or next to the image file or container root directory, all settings will take effect, however, command line arguments still take precedence over corresponding settings.
If disabled, no .nspawn file is read and no settings except the ones on the command line are in effect.
Added in version 226.
Image Options¶
-D, --directory=
If neither --directory=, nor --image= is specified the directory is determined by searching for a directory named the same as the machine name specified with --machine=. See machinectl(1) section "Files and Directories" for the precise search path.
In place of the directory path a ".v/" versioned directory may be specified, see systemd.v(7) for details.
If neither --directory=, --image=, nor --machine= are specified, the current directory will be used. May not be specified together with --image=.
--template=
Note that this switch leaves hostname, machine ID and all other settings that could identify the instance unmodified.
Added in version 219.
-x, --ephemeral
Note that this switch leaves hostname, machine ID and all other settings that could identify the instance unmodified. Please note that — as with --template= — taking the temporary snapshot is more efficient on file systems that support subvolume snapshots or 'reflinks' natively ("btrfs" or new "xfs") than on more traditional file systems that do not ("ext4"). Note that the snapshot taken is of the specified directory or subvolume, including all subdirectories and subvolumes below it, but excluding any sub-mounts.
With this option no modifications of the container image are retained. Use --volatile= (described below) for other mechanisms to restrict persistency of container images during runtime.
Added in version 219.
-i, --image=
On GPT images, if an EFI System Partition (ESP) is discovered, it is automatically mounted to /efi (or /boot as fallback) in case a directory by this name exists and is empty.
Partitions encrypted with LUKS are automatically decrypted. Also, on GPT images dm-verity data integrity hash partitions are set up if the root hash for them is specified using the --root-hash= option.
Single file system images (i.e. file systems without a surrounding partition table) can be opened using dm-verity if the integrity data is passed using the --root-hash= and --verity-data= (and optionally --root-hash-sig=) options.
Any other partitions, such as foreign partitions or swap partitions are not mounted. May not be specified together with --directory=, --template=.
In place of the image path a ".v/" versioned directory may be specified, see systemd.v(7) for details.
Added in version 211.
--image-policy=policy
Added in version 254.
--oci-bundle=
Added in version 242.
--read-only
--volatile, --volatile=MODE
Note that if one of the volatile modes is chosen, its effect is limited to the root file system (or /var/ in case of state), and any other mounts placed in the hierarchy are unaffected — regardless if they are established automatically (e.g. the EFI system partition that might be mounted to /efi/ or /boot/) or explicitly (e.g. through an additional command line option such as --bind=, see below). This means, even if --volatile=overlay is used changes to /efi/ or /boot/ are prohibited in case such a partition exists in the container image operated on, and even if --volatile=state is used the hypothetical file /etc/foobar is potentially writable if --bind=/etc/foobar if used to mount it from outside the read-only container /etc/ directory.
The --ephemeral option is closely related to this setting, and provides similar behaviour by making a temporary, ephemeral copy of the whole OS image and executing that. For further details, see above.
The --tmpfs= and --overlay= options provide similar functionality, but for specific sub-directories of the OS image only. For details, see below.
This option provides similar functionality for containers as the "systemd.volatile=" kernel command line switch provides for host systems. See kernel-command-line(7) for details.
Note that setting this option to yes or state will only work correctly with operating systems in the container that can boot up with only /usr/ mounted, and are able to automatically populate /var/ (and /etc/ in case of "--volatile=yes"). Specifically, this means that operating systems that follow the historic split of /bin/ and /lib/ (and related directories) from /usr/ (i.e. where the former are not symlinks into the latter) are not supported by "--volatile=yes" as container payload. The overlay option does not require any particular preparations in the OS, but do note that "overlayfs" behaviour differs from regular file systems in a number of ways, and hence compatibility is limited.
Added in version 216.
--root-hash=
Note that this configures the root hash for the root file system. Disk images may also contain separate file systems for the /usr/ hierarchy, which may be Verity protected as well. The root hash for this protection may be configured via the "user.verity.usrhash" extended file attribute or via a .usrhash file adjacent to the disk image, following the same format and logic as for the root hash for the root file system described here. Note that there's currently no switch to configure the root hash for the /usr/ from the command line.
Also see the RootHash= option in systemd.exec(5).
Added in version 233.
--root-hash-sig=
Added in version 246.
--verity-data=
Added in version 246.
--pivot-root=
This is for containers which have several bootable directories in them; for example, several OSTree[4] deployments. It emulates the behavior of the boot loader and the initrd which normally select which directory to mount as the root and start the container's PID 1 in.
Added in version 233.
Execution Options¶
-a, --as-pid2
Added in version 229.
-b, --boot
The following table explains the different modes of invocation and relationship to --as-pid2 (see above):
Table 1. Invocation Mode
Switch | Explanation |
Neither --as-pid2 nor --boot specified | The passed parameters are interpreted as the command line, which is executed as PID 1 in the container. |
--as-pid2 specified | The passed parameters are interpreted as the command line, which is executed as PID 2 in the container. A stub init process is run as PID 1. |
--boot specified | An init program is automatically searched for and run as PID 1 in the container. The passed parameters are used as invocation parameters for this process. |
Note that
--boot is the default mode of operation if the systemd-nspawn@.service
template unit file is used.
--chdir=
Added in version 229.
-E NAME[=VALUE], --setenv=NAME[=VALUE]
Added in version 209.
-u, --user=
Note that if credentials are used in combination with a non-root --user= (e.g.: --set-credential=, --load-credential= or --import-credential=), then --no-new-privileges=yes must be used, and --boot or --as-pid2 must not be used, as the credentials would otherwise be unreadable by the container due to missing privileges after switching to the specified user.
--kill-signal=
Added in version 220.
--notify-ready=
Added in version 231.
--suppress-sync=
Added in version 250.
System Identity Options¶
-M, --machine=
Added in version 202.
--hostname=
Added in version 239.
--uuid=
Property Options¶
-S, --slice=
Added in version 206.
--property=
Added in version 220.
--register=
Added in version 209.
--keep-unit
Note that passing --keep-unit disables the effect of --slice= and --property=. Use --keep-unit and --register=no in combination to disable any kind of unit allocation or registration with systemd-machined.
Added in version 209.
User Namespacing Options¶
--private-users=
It is recommended to assign at least 65536 UIDs/GIDs to each container, so that the usable UID/GID range in the container covers 16 bit. For best security, do not assign overlapping UID/GID ranges to multiple containers. It is hence a good idea to use the upper 16 bit of the host 32-bit UIDs/GIDs as container identifier, while the lower 16 bit encode the container UID/GID used. This is in fact the behavior enforced by the --private-users=pick option.
When user namespaces are used, the GID range assigned to each container is always chosen identical to the UID range.
In most cases, using --private-users=pick is the recommended option as it enhances container security massively and operates fully automatically in most cases.
Note that the picked UID/GID range is not written to /etc/passwd or /etc/group. In fact, the allocation of the range is not stored persistently anywhere, except in the file ownership of the files and directories of the container.
Note that when user namespacing is used file ownership on disk reflects this, and all of the container's files and directories are owned by the container's effective user and group IDs. This means that copying files from and to the container image requires correction of the numeric UID/GID values, according to the UID/GID shift applied.
Added in version 220.
--private-users-ownership=
If "chown" is selected, all files and directories in the container's directory tree will be adjusted so that they are owned by the appropriate UIDs/GIDs selected for the container (see above). This operation is potentially expensive, as it involves iterating through the full directory tree of the container. Besides actual file ownership, file ACLs are adjusted as well.
Typically "map" is the best choice, since it transparently maps UIDs/GIDs in memory as needed without modifying the image, and without requiring an expensive recursive adjustment operation. However, it is not available for all file systems, currently.
The --private-users-ownership=auto option is implied if --private-users=pick is used. This option has no effect if user namespacing is not used.
Added in version 230.
-U
Note that -U is the default if the systemd-nspawn@.service template unit file is used.
Note: it is possible to undo the effect of --private-users-ownership=chown (or -U) on the file system by redoing the operation with the first UID of 0:
systemd-nspawn ... --private-users=0 --private-users-ownership=chown
Added in version 230.
Networking Options¶
--private-network
--network-interface=
Note that any network interface specified this way must already exist at the time the container is started. If the container shall be started automatically at boot via a systemd-nspawn@.service unit file instance, it might hence make sense to add a unit file drop-in to the service instance (e.g. /etc/systemd/system/systemd-nspawn@foobar.service.d/50-network.conf) with contents like the following:
[Unit] Wants=sys-subsystem-net-devices-ens1.device After=sys-subsystem-net-devices-ens1.device
This will make sure that activation of the container service will be delayed until the "ens1" network interface has shown up. This is required since hardware probing is fully asynchronous, and network interfaces might be discovered only later during the boot process, after the container would normally be started without these explicit dependencies.
Added in version 209.
--network-macvlan=
As with --network-interface=, the underlying Ethernet network interface must already exist at the time the container is started, and thus similar unit file drop-ins as described above might be useful.
Added in version 211.
--network-ipvlan=
As with --network-interface=, the underlying Ethernet network interface must already exist at the time the container is started, and thus similar unit file drop-ins as described above might be useful.
Added in version 219.
-n, --network-veth
Note that systemd-networkd.service(8) includes by default a network file /usr/lib/systemd/network/80-container-ve.network matching the host-side interfaces created this way, which contains settings to enable automatic address provisioning on the created virtual link via DHCP, as well as automatic IP routing onto the host's external network interfaces. It also contains /usr/lib/systemd/network/80-container-host0.network matching the container-side interface created this way, containing settings to enable client side address assignment via DHCP. In case systemd-networkd is running on both the host and inside the container, automatic IP communication from the container to the host is thus available, with further connectivity to the external network.
Note that --network-veth is the default if the systemd-nspawn@.service template unit file is used.
Note that on Linux network interface names may have a length of 15 characters at maximum, while container names may have a length up to 64 characters. As this option derives the host-side interface name from the container name the name is possibly truncated. Thus, care needs to be taken to ensure that interface names remain unique in this case, or even better container names are generally not chosen longer than 12 characters, to avoid the truncation. If the name is truncated, systemd-nspawn will automatically append a 4-digit hash value to the name to reduce the chance of collisions. However, the hash algorithm is not collision-free. (See systemd.net-naming-scheme(7) for details on older naming algorithms for this interface). Alternatively, the --network-veth-extra= option may be used, which allows free configuration of the host-side interface name independently of the container name — but might require a bit more additional configuration in case bridging in a fashion similar to --network-bridge= is desired.
Added in version 209.
--network-veth-extra=
Added in version 228.
--network-bridge=
As with --network-interface=, the underlying bridge network interface must already exist at the time the container is started, and thus similar unit file drop-ins as described above might be useful.
Added in version 209.
--network-zone=
This setting makes it easy to place multiple related containers on a common, virtual Ethernet-based broadcast domain, here called a "zone". Each container may only be part of one zone, but each zone may contain any number of containers. Each zone is referenced by its name. Names may be chosen freely (as long as they form valid network interface names when prefixed with "vz-"), and it is sufficient to pass the same name to the --network-zone= switch of the various concurrently running containers to join them in one zone.
Note that systemd-networkd.service(8) includes by default a network file /usr/lib/systemd/network/80-container-vz.network matching the bridge interfaces created this way, which contains settings to enable automatic address provisioning on the created virtual network via DHCP, as well as automatic IP routing onto the host's external network interfaces. Using --network-zone= is hence in most cases fully automatic and sufficient to connect multiple local containers in a joined broadcast domain to the host, with further connectivity to the external network.
Added in version 230.
--network-namespace-path=
Added in version 236.
-p, --port=
Added in version 219.
Security Options¶
--capability=
If the special value of "help" is passed, the program will print known capability names and exit.
This option sets the bounding set of capabilities which also limits the ambient capabilities as given with the --ambient-capability=.
Added in version 186.
--drop-capability=
If the special value of "help" is passed, the program will print known capability names and exit.
This option sets the bounding set of capabilities which also limits the ambient capabilities as given with the --ambient-capability=.
Added in version 209.
--ambient-capability=
All capabilities specified here must be in the set allowed with the --capability= and --drop-capability= options. Otherwise, an error message will be shown.
This option cannot be combined with the boot mode of the container (as requested via --boot).
If the special value of "help" is passed, the program will print known capability names and exit.
Added in version 248.
--no-new-privileges=
Added in version 239.
--system-call-filter=
Added in version 235.
-Z, --selinux-context=
Added in version 209.
-L, --selinux-apifs-context=
Added in version 209.
Resource Options¶
--rlimit=
Added in version 239.
--oom-score-adjust=
Added in version 239.
--cpu-affinity=
Added in version 239.
--personality=
Added in version 209.
Integration Options¶
--resolv-conf=
If set to "off" the /etc/resolv.conf file in the container is left as it is included in the image, and neither modified nor bind mounted over.
If set to "copy-host", the /etc/resolv.conf file from the host is copied into the container, unless the file exists already and is not a regular file (e.g. a symlink). Similarly, if "replace-host" is used the file is copied, replacing any existing inode, including symlinks. Similarly, if "bind-host" is used, the file is bind mounted from the host into the container.
If set to "copy-static", "replace-static" or "bind-static" the static resolv.conf file supplied with systemd-resolved.service(8) (specifically: /usr/lib/systemd/resolv.conf) is copied or bind mounted into the container.
If set to "copy-uplink", "replace-uplink" or "bind-uplink" the uplink resolv.conf file managed by systemd-resolved.service (specifically: /run/systemd/resolve/resolv.conf) is copied or bind mounted into the container.
If set to "copy-stub", "replace-stub" or "bind-stub" the stub resolv.conf file managed by systemd-resolved.service (specifically: /run/systemd/resolve/stub-resolv.conf) is copied or bind mounted into the container.
If set to "delete" the /etc/resolv.conf file in the container is deleted if it exists.
Finally, if set to "auto" the file is left as it is if private networking is turned on (see --private-network). Otherwise, if systemd-resolved.service is running its stub resolv.conf file is used, and if not the host's /etc/resolv.conf file. In the latter cases the file is copied if the image is writable, and bind mounted otherwise.
It's recommended to use "copy-..." or "replace-..." if the container shall be able to make changes to the DNS configuration on its own, deviating from the host's settings. Otherwise "bind" is preferable, as it means direct changes to /etc/resolv.conf in the container are not allowed, as it is a read-only bind mount (but note that if the container has enough privileges, it might simply go ahead and unmount the bind mount anyway). Note that both if the file is bind mounted and if it is copied no further propagation of configuration is generally done after the one-time early initialization (this is because the file is usually updated through copying and renaming). Defaults to "auto".
Added in version 239.
--timezone=
Added in version 239.
--link-journal=
Note that --link-journal=try-guest is the default if the systemd-nspawn@.service template unit file is used.
Added in version 187.
-j
Added in version 187.
Mount Options¶
--bind=, --bind-ro=
Mount options are comma-separated. rbind and norbind control whether to create a recursive or a regular bind mount. Defaults to rbind. noidmap, idmap, rootidmap and owneridmap control ID mapping.
Using idmap, rootidmap or owneridmap requires support by the source filesystem for user/group ID mapped mounts. Defaults to noidmap. With x being the container's UID range offset, y being the length of the container's UID range, and p being the owner UID of the bind mount source inode on the host:
Whichever ID mapping option is used, the same mapping will be used for users and groups IDs. If rootidmap or owneridmap are used, the group owning the bind mounted directory will have no effect.
Note that when this option is used in combination with --private-users, the resulting mount points will be owned by the nobody user. That's because the mount and its files and directories continue to be owned by the relevant host users and groups, which do not exist in the container, and thus show up under the wildcard UID 65534 (nobody). If such bind mounts are created, it is recommended to make them read-only, using --bind-ro=. Alternatively you can use the "idmap" mount option to map the filesystem IDs.
Added in version 198.
--bind-user=
The combination of the three operations above ensures that it is possible to log into the container using the same account information as on the host. The user is only mapped transiently, while the container is running, and the mapping itself does not result in persistent changes to the container (except maybe for log messages generated at login time, and similar). Note that in particular the UID/GID assignment in the container is not made persistently. If the user is mapped transiently, it is best to not allow the user to make persistent changes to the container. If the user leaves files or directories owned by the user, and those UIDs/GIDs are reused during later container invocations (possibly with a different --bind-user= mapping), those files and directories will be accessible to the "new" user.
The user/group record mapping only works if the container contains systemd 249 or newer, with nss-systemd properly configured in nsswitch.conf. See nss-systemd(8) for details.
Note that the user record propagated from the host into the container will contain the UNIX password hash of the user, so that seamless logins in the container are possible. If the container is less trusted than the host it's hence important to use a strong UNIX password hash function (e.g. yescrypt or similar, with the "$y$" hash prefix).
When binding a user from the host into the container checks are executed to ensure that the username is not yet known in the container. Moreover, it is checked that the UID/GID allocated for it is not currently defined in the user/group databases of the container. Both checks directly access the container's /etc/passwd and /etc/group, and thus might not detect existing accounts in other databases.
This operation is only supported in combination with --private-users=/-U.
Added in version 249.
--inaccessible=
Added in version 242.
--tmpfs=
Note that this option cannot be used to replace the root file system of the container with a temporary file system. However, the --volatile= option described below provides similar functionality, with a focus on implementing stateless operating system images.
Added in version 214.
--overlay=, --overlay-ro=
Backslash escapes are interpreted in the paths, so "\:" may be used to embed colons in the paths.
If three or more paths are specified, then the last specified path is the destination mount point in the container, all paths specified before refer to directory trees on the host and are combined in the specified order into one overlay file system. The left-most path is hence the lowest directory tree, the second-to-last path the highest directory tree in the stacking order. If --overlay-ro= is used instead of --overlay=, a read-only overlay file system is created. If a writable overlay file system is created, all changes made to it are written to the highest directory tree in the stacking order, i.e. the second-to-last specified.
If only two paths are specified, then the second specified path is used both as the top-level directory tree in the stacking order as seen from the host, as well as the mount point for the overlay file system in the container. At least two paths have to be specified.
The source paths may optionally be prefixed with "+" character. If so they are taken relative to the image's root directory. The uppermost source path may also be specified as an empty string, in which case a temporary directory below the host's /var/tmp/ is used. The directory is removed automatically when the container is shut down. This behaviour is useful in order to make read-only container directories writable while the container is running. For example, use "--overlay=+/var::/var" in order to automatically overlay a writable temporary directory on a read-only /var/ directory. If a source path is not absolute, it is resolved relative to the current working directory.
For details about overlay file systems, see Overlay Filesystem[5]. Note that the semantics of overlay file systems are substantially different from normal file systems, in particular regarding reported device and inode information. Device and inode information may change for a file while it is being written to, and processes might see out-of-date versions of files at times. Note that this switch automatically derives the "workdir=" mount option for the overlay file system from the top-level directory tree, making it a sibling of it. It is hence essential that the top-level directory tree is not a mount point itself (since the working directory must be on the same file system as the top-most directory tree). Also note that the "lowerdir=" mount option receives the paths to stack in the opposite order of this switch.
Note that this option cannot be used to replace the root file system of the container with an overlay file system. However, the --volatile= option described above provides similar functionality, with a focus on implementing stateless operating system images.
Added in version 220.
Input/Output Options¶
--console=MODE
In pipe mode, /dev/console will not exist in the container. This means that the container payload generally cannot be a full init system as init systems tend to require /dev/console to be available. On the other hand, in this mode container invocations can be used within shell pipelines. This is because intermediary pseudo TTYs do not permit independent bidirectional propagation of the end-of-file (EOF) condition, which is necessary for shell pipelines to work correctly. Note that the pipe mode should be used carefully, as passing arbitrary file descriptors to less trusted container payloads might open up unwanted interfaces for access by the container payload. For example, if a passed file descriptor refers to a TTY of some form, APIs such as TIOCSTI may be used to synthesize input that might be used for escaping the container. Hence pipe mode should only be used if the payload is sufficiently trusted or when the standard input/output/error output file descriptors are known safe, for example pipes.
Added in version 242.
--pipe, -P
Added in version 242.
--background=COLOR
Added in version 256.
Credentials¶
--load-credential=ID:PATH, --set-credential=ID:VALUE
Note: when systemd-nspawn runs as systemd system service it can propagate the credentials it received via LoadCredential=/SetCredential= to the container payload. A systemd service manager running as PID 1 in the container can further propagate them to the services it itself starts. It is thus possible to easily propagate credentials from a parent service manager to a container manager service and from there into its payload. This can even be done recursively.
In order to embed binary data into the credential data for --set-credential=, use C-style escaping (i.e. "\n" to embed a newline, or "\x00" to embed a NUL byte). Note that the invoking shell might already apply unescaping once, hence this might require double escaping!
The systemd-sysusers.service(8) and systemd-firstboot(1) services read credentials configured this way for the purpose of configuring the container's root user's password and shell, as well as system locale, keymap and timezone during the first boot process of the container. This is particularly useful in combination with --volatile=yes where every single boot appears as first boot, since configuration applied to /etc/ is lost on container reboot cycles. See the respective man pages for details. Example:
# systemd-nspawn -i image.raw \
--volatile=yes \
--set-credential=firstboot.locale:de_DE.UTF-8 \
--set-credential=passwd.hashed-password.root:'$y$j9T$yAuRJu1o5HioZAGDYPU5d.$F64ni6J2y2nNQve90M/p0ZP0ECP/qqzipNyaY9fjGpC' \
-b
The above command line will invoke the specified image file image.raw in volatile mode, i.e. with empty /etc/ and /var/. The container payload will recognize this as a first boot, and will invoke systemd-firstboot.service, which then reads the two passed credentials to configure the system's initial locale and root password.
Added in version 247.
Other¶
--no-pager
-h, --help
--version
ENVIRONMENT¶
$SYSTEMD_LOG_LEVEL
$SYSTEMD_LOG_COLOR
This setting is only useful when messages are written directly to the terminal, because journalctl(1) and other tools that display logs will color messages based on the log level on their own.
$SYSTEMD_LOG_TIME
This setting is only useful when messages are written directly to the terminal or a file, because journalctl(1) and other tools that display logs will attach timestamps based on the entry metadata on their own.
$SYSTEMD_LOG_LOCATION
Note that the log location is often attached as metadata to journal entries anyway. Including it directly in the message text can nevertheless be convenient when debugging programs.
$SYSTEMD_LOG_TID
Note that the this information is attached as metadata to journal entries anyway. Including it directly in the message text can nevertheless be convenient when debugging programs.
$SYSTEMD_LOG_TARGET
$SYSTEMD_LOG_RATELIMIT_KMSG
$SYSTEMD_PAGER
Note: if $SYSTEMD_PAGERSECURE is not set, $SYSTEMD_PAGER (as well as $PAGER) will be silently ignored.
$SYSTEMD_LESS
Users might want to change two options in particular:
K
If the value of $SYSTEMD_LESS does not include "K", and the pager that is invoked is less, Ctrl+C will be ignored by the executable, and needs to be handled by the pager.
X
Note that setting the regular $LESS environment variable has no effect for less invocations by systemd tools.
See less(1) for more discussion.
$SYSTEMD_LESSCHARSET
Note that setting the regular $LESSCHARSET environment variable has no effect for less invocations by systemd tools.
$SYSTEMD_PAGERSECURE
Note: when commands are invoked with elevated privileges, for example under sudo(8) or pkexec(1), care must be taken to ensure that unintended interactive features are not enabled. "Secure" mode for the pager may be enabled automatically as describe above. Setting SYSTEMD_PAGERSECURE=0 or not removing it from the inherited environment allows the user to invoke arbitrary commands. Note that if the $SYSTEMD_PAGER or $PAGER variables are to be honoured, $SYSTEMD_PAGERSECURE must be set too. It might be reasonable to completely disable the pager using --no-pager instead.
$SYSTEMD_COLORS
$SYSTEMD_URLIFY
EXAMPLES¶
Example 1. Download an Ubuntu TAR image and open a shell in it
# importctl pull-tar -mN https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64-root.tar.xz # systemd-nspawn -M jammy-server-cloudimg-amd64-root
This downloads and verifies the specified .tar image, and then uses systemd-nspawn(1) to open a shell in it.
Example 2. Build and boot a minimal Fedora distribution in a container
# dnf -y --releasever=40 --installroot=/var/lib/machines/f40 \
--repo=fedora --repo=updates --setopt=install_weak_deps=False install \
passwd dnf fedora-release vim-minimal util-linux systemd systemd-networkd # systemd-nspawn -bD /var/lib/machines/f40
This installs a minimal Fedora distribution into the directory /var/lib/machines/f40 and then boots that OS in a namespace container. Because the installation is located underneath the standard /var/lib/machines/ directory, it is also possible to start the machine using systemd-nspawn -M f40.
Example 3. Spawn a shell in a container of a minimal Debian unstable distribution
# debootstrap unstable ~/debian-tree/ # systemd-nspawn -D ~/debian-tree/
This installs a minimal Debian unstable distribution into the directory ~/debian-tree/ and then spawns a shell from this image in a namespace container.
debootstrap supports Debian[7], Ubuntu[8], and Tanglu[9] out of the box, so the same command can be used to install any of those. For other distributions from the Debian family, a mirror has to be specified, see debootstrap(8).
Example 4. Boot a minimal Arch Linux distribution in a container
# pacstrap -c ~/arch-tree/ base # systemd-nspawn -bD ~/arch-tree/
This installs a minimal Arch Linux distribution into the directory ~/arch-tree/ and then boots an OS in a namespace container in it.
Example 5. Install the OpenSUSE Tumbleweed rolling distribution
# zypper --root=/var/lib/machines/tumbleweed ar -c \
https://download.opensuse.org/tumbleweed/repo/oss tumbleweed # zypper --root=/var/lib/machines/tumbleweed refresh # zypper --root=/var/lib/machines/tumbleweed install --no-recommends \
systemd shadow zypper openSUSE-release vim # systemd-nspawn -M tumbleweed passwd root # systemd-nspawn -M tumbleweed -b
Example 6. Boot into an ephemeral snapshot of the host system
# systemd-nspawn -D / -xb
This runs a copy of the host system in a snapshot which is removed immediately when the container exits. All file system changes made during runtime will be lost on shutdown, hence.
Example 7. Run a container with SELinux sandbox security contexts
# chcon system_u:object_r:svirt_sandbox_file_t:s0:c0,c1 -R /srv/container # systemd-nspawn -L system_u:object_r:svirt_sandbox_file_t:s0:c0,c1 \
-Z system_u:system_r:svirt_lxc_net_t:s0:c0,c1 -D /srv/container /bin/sh
Example 8. Run a container with an OSTree deployment
# systemd-nspawn -b -i ~/image.raw \
--pivot-root=/ostree/deploy/$OS/deploy/$CHECKSUM:/sysroot \
--bind=+/sysroot/ostree/deploy/$OS/var:/var
EXIT STATUS¶
The exit code of the program executed in the container is returned.
SEE ALSO¶
systemd(1), systemd.nspawn(5), chroot(1), dnf(8), debootstrap(8), pacman(8), zypper(8), systemd.slice(5), machinectl(1), importctl(1), systemd-mountfsd.service(8), systemd-nsresourced.service(8), btrfs(8)
NOTES¶
- 1.
- Container Interface
- 2.
- Discoverable Partitions Specification
- 3.
- OCI Runtime Specification
- 4.
- OSTree
- 5.
- Overlay Filesystem
- 6.
- ANSI Escape Code (Wikipedia)
- 7.
- Debian
- 8.
- Ubuntu
- 9.
- Tanglu
- 10.
- Arch Linux
- 11.
- OpenSUSE Tumbleweed
systemd 256.7 |