How to Run Systemctl Command Inside Docker Container?

How to Run Systemctl Command Inside Docker Container?

I would like to run a docker container which will have the ability to run systemctl commands on its host.

Following this question I didn't find a solution that would work for me.

I have no hard limits on the docker base image, so using ubuntu-16.04 docker image for an ubuntu-16.04 host and ubuntu-18.04 docker image for an ubuntu-18.04 host is totally acceptable.

3 Answers

After some investigation I was able to run a docker container with the ability to run systemctl command.

  1. The following worked when running on an ubuntu:16.04 host:

    • sudo docker run --privileged -v /run/systemd/system:/run/systemd/system -v /bin/systemctl:/bin/systemctl -v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket -it ubuntu:16.04 systemctl
      
    • sudo docker run --privileged -v /run/systemd/system:/run/systemd/system -v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket -it ubuntu:16.04 systemctl
      
  2. And on ubuntu:18.04 host:

    sudo docker run --privileged -v /run/systemd/system:/run/systemd/system -v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket -it ubuntu:18.04 systemctl
    

    Since systemctl doesn't come with this image

2

Thanks ofirule

Tried your solution on debian:10, your solution effectively allows to run the systemctl but it won't allow it to see/control the host's systemd processes. For this to work the /sys/fs/cgroup directory must also be mounted as a volume:

docker run -it --rm -v /bin/systemctl:/bin/systemctl -v /run/systemd/system:/run/systemd/system -v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket -v /sys/fs/cgroup:/sys/fs/cgroup debian:10 systemctl --no-pager status

With this i can control the host's systemd services and even do a shutdown/reboot through systemd.

This seems specific to Debian 10 and not needed for Ubuntu 18.04. Other Debian/Ubuntu versions might or might not need it.

3

Not allowed to comment. But this worked for my Ubuntu 18.04 setup:

sudo docker run --privileged \
-v /run/systemd/system:/run/systemd/system \
-v /lib/:/lib/ \
-v /usr/lib/x86_64-linux-gnu/:/usr/lib/x86_64-linux-gnu/ \
-v /bin/systemctl:/bin/systemctl \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket \
-it ubuntu:18.04 /bin/sh -c "systemctl restart openvpn.service; systemctl status openvpn.service"

If the command complains about error while loading shared libraries: libip4tc.so.0: -> run locate libip4tc.so.0 to find out where this file is and mount the folder as a volume.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.