Docker-compose on boot

Often it may be useful for a docker-compose file to be executed on boot, for example when you do not want to set restart: always. Here is a brief and easy way to achieve this through systemd.

Create a systemd unit file with .service extension in /etc/systemd/system, for example /etc/systemd/system/swag.service, with the following content:

[Unit]
Description=Swag docker #Description for the service
Requires=docker.service
After=docker.service

[Service]
Restart=always
User=root
Group=docker
WorkingDirectory=/home/ryan/swag #Directory the docker-compose file is in
ExecStartPre=docker-compose -f docker-compose.yml down
ExecStart=docker-compose -f docker-compose.yml up
ExecStop=docker-compose -f docker-compose.yml down

[Install]
WantedBy=multi-user.target

After this, assuming that your docker-compose file exists without issue, you should be able to start the service with: systemctl start swag. To enable this to startup at boot use: systemctl enable swag.

Explanation

The lines that truly let this work are the following: Requires=docker.service and After=docker.service. These instruct the system to wait for docker to start and then attempt to start the service.

The next line we need is the WorkingDirectory=/home/ryan/swag line. Without this, the docker-compose file cannot be found.

Linked here is a script that creates a service that does exactly this from the current working directory. (Not made by me)

Mastodon