Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add doker-compose as a systemd unit

Docker compose as a systemd unit

Create file /etc/systemd/system/docker-compose@.service

[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

@burningTyger

This comment has been minimized.

burningTyger commented Oct 23, 2017

some distros have /usr/local/bin for docker-compose …

@daswars

This comment has been minimized.

daswars commented Sep 4, 2018

Hi, I don't understand why the volumes are also deleted.
Now the persistent storage is gone

@cigzigwon

This comment has been minimized.

cigzigwon commented Oct 17, 2018

@daswars I agree with you. All of the bash exec commands are not needed unless you want to clear out everything such as stateful task runners. But if you have a db it will remove all mounted docker volumes which you would want to avoid. Same em.with the networks. docker-compose down will remove them initially.

@janbuecker

This comment has been minimized.

janbuecker commented Nov 19, 2018

The docker-compose path in ExecStartPre is different to ExecStart which could lead to errors.

@xiaket

This comment has been minimized.

xiaket commented Nov 24, 2018

The cleanup could be more conveniently done through cron.

@pr0totyp

This comment has been minimized.

pr0totyp commented Nov 29, 2018

@daswars I also dont understand why the volumes are deleted. You could use bind mount for e.g. /var/lib/postgresql/data. I just removed the commands/parameters deleting volumes.

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