Skip to content

Instantly share code, notes, and snippets.

@tcarreira
Last active February 12, 2021 22:52
Show Gist options
  • Save tcarreira/b7d9c3b8c55ea20c4f3d73e7235bdd2f to your computer and use it in GitHub Desktop.
Save tcarreira/b7d9c3b8c55ea20c4f3d73e7235bdd2f to your computer and use it in GitHub Desktop.
Run my docker-compose as a systemd service.
#!/bin/sh
DOCKER_COMPOSE_PATH="/data/docker"
SERVICE_NAME="my-docker-compose.service"
SCRIPT_NAME="$(realpath "$0")"
echo_service_content() {
cat >&1 <<EOF
[Unit]
Description=Docker Compose service
[Service]
Type=forking
ExecStart="${SCRIPT_NAME}" start
ExecReload="${SCRIPT_NAME}" reload
ExecStop="${SCRIPT_NAME}" stop
RemainAfterExit=yes
GuessMainPID=no
[Install]
WantedBy=multi-user.target
EOF
}
help() {
echo "This script runs the docker-compose service (at ${DOCKER_COMPOSE_PATH})"
echo " or installs the service ($0 install)"
}
install() {
service_file="/etc/systemd/system/${SERVICE_NAME}"
echo "############## replacing old content file at ${service_file}"
cat "$service_file"
echo_service_content >"$service_file"
echo ""
echo "############## Script installed with content:"
cat "$service_file"
systemctl daemon-reload
systemctl enable "${SERVICE_NAME}"
}
start(){
cd "${DOCKER_COMPOSE_PATH}" || exit 1
docker-compose up -d
}
stop(){
cd "${DOCKER_COMPOSE_PATH}" || exit 1
docker-compose stop
}
restart(){
stop
start
}
reload(){
cd "${DOCKER_COMPOSE_PATH}" || exit 1
docker-compose restart
}
status(){
cd "${DOCKER_COMPOSE_PATH}" || exit 1
docker-compose ps
}
#echo "#=#=#=#=#=#= DEBUG: called as $@"
case $1 in
start|stop|restart|reload|status) "$1" ;;
install|help) "$1" ;;
*) status;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment