Automated Deployment with Git Post-Receive Hook
This Git post-receive hook automates the deployment of a Django application on a remote server. Upon pushing code to the bare repository, the hook:
- Checks out the latest code to the application directory.
- Restarts the Docker Compose services, rebuilding images if needed and removing orphan containers.
- Runs Django management commands to collect static files and apply database migrations.
This ensures that the server is always up-to-date with the latest code changes, streamlining deployments and reducing manual steps.
#!/bin/bash
set -e
APP_DIR=/your/app/dir
BARE_REPO=/your/bare/repo
echo "Deployment latest code ..."
if ! git --work-tree=$APP_DIR --git-dir=$BARE_REPO checkout -f; then
echo "❌ Git checkout failed. Deployment aborted."
exit 1
fi
cd $APP_DIR
echo "Restarting docker compose ..."
sudo docker compose down
sudo docker compose up --build --detach --remove-orphans
sudo docker compose run web python manage.py collectstatic --no-input
sudo docker compose run web python manage.py migrate
echo "✅ Deployment finished!"