Skip to content

Instantly share code, notes, and snippets.

@mshafiee
Last active October 19, 2020 11:52
Show Gist options
  • Save mshafiee/06406b9887867366cfdb01f161dea498 to your computer and use it in GitHub Desktop.
Save mshafiee/06406b9887867366cfdb01f161dea498 to your computer and use it in GitHub Desktop.

Docker compose as a systemd unit

Create file /etc/systemd/system/myservice.service. SystemD calling binaries using an absolute path. In my case is prefixed by /usr/local/bin, you should use paths specific for your environment.

[Unit]
Description=%i service with docker compose
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=true
WorkingDirectory=/opt/myservice
ExecStart=/usr/bin/docker-compose up -d --remove-orphans
ExecStop=/usr/bin/docker-compose down

[Install]
WantedBy=multi-user.target

Place your docker-compose.yml into /opt/myservice and call

systemctl start myservice

Docker cleanup timer with system

Create /etc/systemd/system/docker-cleanup.timer with this content:

[Unit]
Description=Docker cleanup timer

[Timer]
OnUnitInactiveSec=12h

[Install]
WantedBy=timers.target

And service file /etc/systemd/system/docker-cleanup.service:

[Unit]
Description=Docker cleanup
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
WorkingDirectory=/tmp
User=root
Group=root
ExecStart=/usr/bin/docker system prune -af

[Install]
WantedBy=multi-user.target

run systemctl enable docker-cleanup.timer for enabling the timer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment