Skip to content

Instantly share code, notes, and snippets.

@ceelsoin
Forked from mosquito/README.md
Last active March 30, 2020 18:27
Show Gist options
  • Save ceelsoin/80b3bf665bfc370238dd26cfdf471269 to your computer and use it in GitHub Desktop.
Save ceelsoin/80b3bf665bfc370238dd26cfdf471269 to your computer and use it in GitHub Desktop.
Add mariadb or other docker-compose as a systemd unit

MariaDB (or others) Docker compose as a systemd unit

Install docker-compose

sudo curl -L "https://github.com/docker/compose/releases/download/1.23.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
docker-compose --version

Create a docker-compose /var/www/containers/yourservice/docker-compose.yml

version: "3.1"
services:

    mariadb:
      image: mariadb:10.4
      container_name: mariadb
      working_dir: /application
      volumes:
        - .:/application
      environment:
        - MYSQL_ROOT_PASSWORD=
        - MYSQL_DATABASE=
        - MYSQL_USER=
        - MYSQL_PASSWORD=
      ports:
        - "3306:3306"

Save and continue...

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

[Install]
WantedBy=multi-user.target


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

[Service]
Restart=always

WorkingDirectory=/var/www/containers/%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
systemctl daemon-reload
sudo systemctl enable docker-compose@yourservice
systemctl start docker-compose@yourservice

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