How to run a command inside a running systemd container

containerssystemd

I have a systemd container running, and I can login into it with machinectl login <container>. How can I execute a command inside the container directly, i.e. without first logging in, executing the command, and then logging out?

Another way to put it is that I'm looking for the systemd equivalent of:

$ docker exec <container> <command> 

or

$ ssh <host> <command>

Best Answer

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)

Related Question