Skip to content

Instantly share code, notes, and snippets.

@garraflavatra
Created March 31, 2024 16:20
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 garraflavatra/f4f1f08a8193faf7807a534569dcae98 to your computer and use it in GitHub Desktop.
Save garraflavatra/f4f1f08a8193faf7807a534569dcae98 to your computer and use it in GitHub Desktop.
Zero-downtime deployment script for Docker Compose, Django, and Nginx.
#!/bin/sh
#
# Zero-downtime deployment script for Docker Compose and Nginx (+ Django)
# Inspired by https://www.tines.com/blog/simple-zero-downtime-deploys-with-nginx-and-docker-compose
#
# (c) Romein van Buren 2024
# SPDX-License-Identifier: WTFPL
#
reload_nginx() {
docker compose exec nginx /usr/sbin/nginx -s reload
}
zero_downtime_deploy() {
service_name=app
old_container_id=$(docker compose ps -q $service_name | tail -n1)
# Bring a new container online, running new code
# (nginx continues routing to the old container only)
docker compose up -d --no-deps --scale $service_name=2 --no-recreate $service_name
# Wait for new container to be available
new_container_id=$(docker ps -q | head -n1)
new_container_ip=$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $new_container_id)
curl --silent --include --retry-connrefused --retry 30 --retry-delay 1 --fail --header "Host: 0.0.0.0" http://$new_container_ip:8000/ > /dev/null || exit 1
# Run migrations and collect static assets
docker exec $new_container_id python manage.py collectstatic --noinput
docker exec $new_container_id python manage.py migrate
# Start routing requests to the new container (as well as the old)
reload_nginx
# Take the old container offline
docker stop $old_container_id
docker rm $old_container_id
docker compose up -d --no-deps --scale $service_name=1 --no-recreate $service_name
# Stop routing requests to the old container
reload_nginx
}
sudo docker build --no-cache -t app:latest .
zero_downtime_deploy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment