Skip to content

Instantly share code, notes, and snippets.

@stigi
Created February 21, 2024 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stigi/b9bfac0292732e874059f555a0dceea5 to your computer and use it in GitHub Desktop.
Save stigi/b9bfac0292732e874059f555a0dceea5 to your computer and use it in GitHub Desktop.
Git Hook: docker compose deploy
#!/usr/bin/env bash
# A git post-receive hook
#
# On main branch only :
# 1. It builds the service via docker compose build
# 2. It then restarts the service by bringing it down and up again (full service reboot)
# Also removes old containers.
#
## --- Config
baseName=$(basename "$(pwd)")
deployDir="../$baseName-deploy"
## --- End Config
mkdir -p "$deployDir"
while read -r _oldrev _newrev refname; do
branch=$(git rev-parse --symbolic --abbrev-ref "$refname")
if [ "main" == "$branch" ]; then
start=$(date +%s)
echo "Hook : Pushed to $branch branch. Proceeding with deploy of $refname ..."
# We're in a bare repo, so let's checkout a working copy
echo "Hook : Checking out to a working copy to $deployDir"
GIT_WORK_TREE=$deployDir git checkout -f main
cd "$deployDir" || exit
# Building using docker compose
if [ ! -f "$deployDir/docker-compose.yml" ]; then
echo "Hook: No docker compose.yml. Skipping deploy."
continue # next in while
fi
# Explicitly pulling all images to speed up later stages by not requiring `--pull`
echo "Docker : Pulling latest images"
if ! docker compose pull; then
echo "Docker : Pull failed, aborting"
continue
fi
echo "Docker : Building images for containers defined with docker compose"
if ! docker compose build; then
echo "Docker : Build failed, aborting"
continue
fi
echo "Docker : Bringing service down and and removing unused containers"
if ! docker compose down --remove-orphans --rmi local; then
echo "Docker : Could not clean up running containers, aborting"
continue
fi
echo "Docker : Bringing service up again"
if ! docker compose up -d; then
echo "Docker : Could bring up the service, aborting"
continue
fi
end=$(date +%s)
echo "Hook : Done deploying in $(($end-$start)) seconds"
fi
done
@stigi
Copy link
Author

stigi commented Feb 21, 2024

This hook lives in a bare git repo on my hetzner server running ubuntu with docker and compose plugin.
I serve all http(s) via Caddy and https://github.com/lucaslorentz/caddy-docker-proxy

I can then easily spin up a new service on a subdomain by pushing a repo with a docker-compose.yml file that looks a little something like this:

version: '3.8'
services:
  test:
    build:
      dockerfile: Dockerfile
    networks:
      - caddy
    labels:
      caddy: test.ullrich.is
      caddy.reverse_proxy: "{{upstreams 4321}}"

networks:
  caddy:
    external: true

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