How to run a command inside a running systemd container

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>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x