Search code examples
dockersystemd

How to start and stop docker container with systemd


I am going to leave the question with answer to help anyone who has similar problem with configuring docker and systemd together.

How we can start and stop docker container with systemd?


Solution

    1. First we will create docker image

      FROM debian:stretch
      
      RUN apt-get update \
          && apt-get install -y systemd \
          && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
      
      RUN rm -f /lib/systemd/system/multi-user.target.wants/* \
          /etc/systemd/system/*.wants/* \
          /lib/systemd/system/local-fs.target.wants/* \
          /lib/systemd/system/sockets.target.wants/*udev* \
          /lib/systemd/system/sockets.target.wants/*initctl* \
          /lib/systemd/system/sysinit.target.wants/systemd-tmpfiles-setup* \
          /lib/systemd/system/systemd-update-utmp*
      
      # systemd should be started with PID 1
      CMD [ "/lib/systemd/systemd" ]
      
    2. Let's build our docker image

    docker build -t test_image path_to_docker_file

    1. Now we can create and start new container

    docker run --name test_container -it -d --privileged --stop-signal RTMIN+3 test_image

    1. Or you can start existing container

    docker start test_image

    1. Now you can attach to running container to execute some bash command for example

    docker exec -it test_container bash

    1. To stop container

    docker stop test_container

    IMPORTANT!!!

    Do not specify ENTRYPOINT when you start container it should be always SYSTEMD, if you want to execute something do it by attaching to container

    docker exec -it test_container bash (or other any commands)

    You cannot start systemd during Docker image build.

    Solution was tested for Docker version 2.0.0.3 on macOS