Skip to content

Instantly share code, notes, and snippets.

@nexus166
Forked from mosquito/README.md
Last active March 28, 2020 05:35
Show Gist options
  • Save nexus166/780c3904c4c0b8b74807b4d11f314acf to your computer and use it in GitHub Desktop.
Save nexus166/780c3904c4c0b8b74807b4d11f314acf to your computer and use it in GitHub Desktop.
Add doker-compose as a systemd unit
cat <<'EOF' > '/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
ExecStartPre=/usr/local/bin/docker-compose down -v
ExecStartPre=/usr/local/bin/docker-compose rm -fv
ExecStartPre=-/bin/bash -xc '/usr/bin/docker volume rm $(/usr/bin/docker volume ls -qf "name=%i_") || true'
ExecStartPre=-/bin/bash -xc '/usr/bin/docker nework rm $(/usr/bin/docker network ls -qf "name=%i_") || true'
ExecStartPre=-/bin/bash -xc '/usr/bin/docker rm $(/usr/bin/docker ps -aqf "name=%i_*") || true'
ExecStart=/usr/local/bin/docker-compose up
ExecStop=/usr/local/bin/docker-compose down -v

[Install]
WantedBy=multi-user.target
EOF

Place docker-compose.ymls into /etc/docker/compose/myservice and

systemctl enable docker-compose@myservice
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