Building Zero-Downtime Application Deployments using Docker & Nginx
In production web applications, restarting a single container during code updates causes brief connection drops (502 Bad Gateway errors). Implementing a Blue-Green Deployment strategy allows you to launch updated application containers alongside active ones and switch traffic seamlessly with zero downtime.
1. Blue-Green Container Architecture
Instead of overwriting a live container, we run two identical container ports:
- Blue Container: Active container receiving user traffic on port
8001. - Green Container: Staging container running updated code on port
8002.
2. Setting Up Nginx Upstream Switching
Configure Nginx to proxy requests to an active upstream configuration block in /etc/nginx/conf.d/app.conf:
upstream app_backend {
# Dynamically toggled via automation script between 8001 and 8002
server 127.0.0.1:8001;
}
server {
listen 80;
server_name app.yourdomain.com;
location / {
proxy_pass http://app_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
3. Automated Deployment Shell Script
Use the following Bash deployment script (deploy.sh) to spin up new builds, run health checks, and swap Nginx upstreams automatically:
#!/bin/bash
set -e
NEW_PORT=8002
OLD_PORT=8001
echo "==> Building and starting new container version on port $NEW_PORT..."
docker run -d --name app_green -p $NEW_PORT:8000 myapp:latest
echo "==> Waiting for container health check..."
sleep 5
if curl -s http://localhost:$NEW_PORT/health | grep -q "OK"; then
echo "==> Health check passed. Switching Nginx upstream..."
sed -i "s/$OLD_PORT/$NEW_PORT/g" /etc/nginx/conf.d/app.conf
sudo systemctl reload nginx
echo "==> Stopping legacy container..."
docker stop app_blue && docker rm app_blue
echo "==> Zero-downtime deployment complete!"
else
echo "==> Health check failed! Rolling back..."
docker stop app_green && docker rm app_green
exit 1
fi
Comments