Skip to content

Instantly share code, notes, and snippets.

@tomgidden
Created October 19, 2024 03:18
Show Gist options
  • Save tomgidden/9aa597f14a320a52fb9b424078f6f7a7 to your computer and use it in GitHub Desktop.
Save tomgidden/9aa597f14a320a52fb9b424078f6f7a7 to your computer and use it in GitHub Desktop.
systemd file for docker compose, with added dereference of symlinks
[Unit]
Description=%i service with docker compose
Requires=docker.service
After=docker.service network-online.target autofs.service
[Service]
Type=oneshot
RemainAfterExit=true
WorkingDirectory=/etc/docker/compose/%i
ExecStart=/bin/sh -c 'cd "$(dirname $(realpath /etc/docker/compose/%i/compose.yml))" && docker compose up -d --remove-orphans'
ExecStop=/bin/sh -c 'cd "$(dirname $(realpath /etc/docker/compose/%i/compose.yml))" && docker compose down'
[Install]
WantedBy=multi-user.target
@tomgidden
Copy link
Author

The idea here is that you have a dir called /etc/docker/compose/«project» for each compose project. That's what the typical [email protected] file does.

However, it borks if the compose file in there is a symlink; this is useful if you want the actual compose project somewhere else on the server. You can symlink the whole project file as /etc/docker/compose/«project», but that's still not that tidy, and Compose still thinks it's running in /etc which may break relative paths.

Instead, symlink the compose file as /etc/docker/compose/«project»/compose.yml (apparently the primary name for that file) and this version of the service file will resolve the symlink first and chdir.

Save this file to /etc/systemd/system/[email protected] and something like:

systemctl daemon-reload

mkdir /etc/docker/compose/traefik
ln -s /projects/traefik/compose.yml /etc/docker/compose/traefik/compose.yml

systemctl enable docker-compose@traefik
systemctl start docker-compose@traefik

It might not handle paths with spaces and weird chars, so keep it simple. Improvements welcome.

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