I’ve recently been moving a few of my services from bare metal installations over to docker containers. Normally I use ansible to deploy everything in the right place (and you should be doing that too), but I have a “playground” to try out stuff before promoting it to “properly deployed on a different VM with ansible”.
The following script came in handy to simplify the process of creating systemd service files for the docker services.
It assumes that you are in a directory with a docker-compose.yml and the directory name will be the service name, e.g. you are in /opt/watchtower/ and there is a docker-compose.yml here -> the service name will be watchtower .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #!/usr/bin/env bash if [[ ! -r ./docker-compose.yml ]]; then echo "Switch into the directory with your docker-compose.yml file" exit fi _Service="${PWD##*/}" _dockerCompose="$(type -p docker-compose)" echo "Creating /etc/systemd/system/${_Service}.service" cat >/etc/systemd/system/${_Service}.service <<_EOF_ [Unit] Description=${_Service} Requires=docker.service After=docker.service [Service] Restart=always User=root Group=docker WorkingDirectory=${PWD} ExecStartPre=${_dockerCompose} -f docker-compose.yml down ExecStart=${_dockerCompose} -f docker-compose.yml up ExecStop=${_dockerCompose} -f docker-compose.yml down [Install] WantedBy=multi-user.target _EOF_ echo "Enabling & starting ${_Service}" systemctl daemon-reload systemctl enable ${_Service}.service systemctl start ${_Service}.service |