Created
February 21, 2024 21:32
-
-
Save stigi/b9bfac0292732e874059f555a0dceea5 to your computer and use it in GitHub Desktop.
Git Hook: docker compose deploy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: