Skip to content

Instantly share code, notes, and snippets.

@un1ko85
Forked from mosquito/README.md
Created April 23, 2020 15:41
Show Gist options
  • Save un1ko85/0c505193b8b61455da8f160526e1ac73 to your computer and use it in GitHub Desktop.
Save un1ko85/0c505193b8b61455da8f160526e1ac73 to your computer and use it in GitHub Desktop.
Add doker-compose as a systemd unit

Docker compose as a systemd unit

Create file /etc/systemd/system/[email protected]

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

[Service]
Restart=always

WorkingDirectory=/etc/docker/compose/%i

# Remove old containers, images and volumes
ExecStartPre=/usr/local/bin/docker-compose down -v
ExecStartPre=/usr/local/bin/docker-compose rm -fv
ExecStartPre=-/bin/bash -c 'docker volume ls -qf "name=%i_" | xargs docker volume rm'
ExecStartPre=-/bin/bash -c 'docker network ls -qf "name=%i_" | xargs docker network rm'
ExecStartPre=-/bin/bash -c 'docker ps -aqf "name=%i_*" | xargs docker rm'

# Compose up
ExecStart=/usr/bin/docker-compose up

# Compose down, remove containers and volumes
ExecStop=/usr/bin/docker-compose down -v

[Install]
WantedBy=multi-user.target

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

systemctl start docker-compose@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 -f

[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