Automate docker compose startups

From snippet wiki
Jump to: navigation, search

Initial automated startup

For automated startup of your docker containers using docker-compose and systemd:

Suppose you have a tree in your filesystem (/root/dockers/) from where you have subfolders for each docker-compose project, containing the usual docker-compose.yml.

We have to create a template systemd file in /etc/systemd/system/ and enable each stack to use that. So the template file will be named docker-compose@.service (mind that dot in the name):

[Unit]
Description=Docker Compose container starter %i
After=docker.service network-online.target
Requires=docker.service network-online.target
 
[Service]
WorkingDirectory=/root/dockers/%i
Type=oneshot
RemainAfterExit=yes
 
ExecStartPre=-/usr/local/bin/docker-compose pull --quiet
ExecStart=/usr/local/bin/docker-compose up -d
 
ExecStop=/usr/local/bin/docker-compose down
 
ExecReload=/usr/local/bin/docker-compose pull --quiet
ExecReload=/usr/local/bin/docker-compose up -d
 
[Install]
WantedBy=multi-user.target

The variable %i will be replaced by the instance name.

systemctl enable docker-compose@wordpress.service

We now created a symlink for that docker compose stack. Just start the service as usual:

systemctl start docker-compose@wordpress.service

Regular automated image refresh

To automate any new pull requests from your docker hub you can even create docker-compose-reload.timer

[Unit]
Description=Refresh images and update containers
Requires=docker-compose.service
After=docker-compose.service
 
[Timer]
OnCalendar=*:0/15
 
[Install]
WantedBy=timers.target

And a docker-compose-reload.service file

[Unit]
Description=Refresh images and update containers
 
[Service]
Type=oneshot
 
ExecStart=/bin/systemctl reload-or-restart docker-compose@wpfpm.service
 
[Install]
WantedBy=docker-compose@wpfpm.service

Now you will keep up to date.

Autoren der Seite / Contributors of the page

» Kai Kretschmann, (google+)