How to run a command inside a running systemd container

Try systemd-run:

# systemd-nspawn -D <machine-root> -b 3 --link-journal host

# systemd-run --machine <machine-name> env
Running as unit run-1356.service.

# journalctl --machine <machine-name> -u run-1356 -b -q
Oct 30 07:45:09 jessie-64 systemd[1]: Started /usr/bin/env.
Oct 30 07:45:09 jessie-64 env[37]: PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Excerpt from the manpage:

Use shell (see below) or systemd-run(1) with the --machine= switch to directly invoke a single command, either interactively or in the background.

(The command shell available since v225)


For systems without machinectl shell (e.g. systemd v219 on CentOS 7 Atomic) or during situations where machinectl login fails for any reason, you can get a shell or run commands directly using nsenter:

Example:

$ nsenter \
     --target=$(machinectl show --property Leader ipsec-libreswan | sed "s/^Leader=//") \
     --mount --uts --ipc --net --pid