What is Blue-Green Deployment?
You maintain two identical production environments:
- Blue — currently serving live traffic
- Green — idle, ready for the next deployment
┌──── Blue (v1.0) ← Live traffic
Router ──┤
└──── Green (v1.1) ← Deploy here, test, then switch
How It Works
- Deploy new version to Green (Blue still serves traffic)
- Run smoke tests against Green
- Switch the router to point to Green
- Green is now live, Blue is idle
- If anything goes wrong, switch back to Blue (instant rollback)
Implementation with Nginx
# /etc/nginx/conf.d/upstream.conf
upstream app_blue {
server 127.0.0.1:3001;
}
upstream app_green {
server 127.0.0.1:3002;
}
# Active environment (change this to switch)
upstream app_active {
server 127.0.0.1:3001; # Blue is active
}
server {
listen 443 ssl;
server_name example.com;
location / {
proxy_pass http://app_active;
}
}
Switching
# Switch to Green
sed -i 's/3001/3002/' /etc/nginx/conf.d/upstream.conf
sudo nginx -t && sudo nginx -s reload
# Rollback to Blue
sed -i 's/3002/3001/' /etc/nginx/conf.d/upstream.conf
sudo nginx -t && sudo nginx -s reload
Deployment Script
#!/bin/bash
# deploy.sh
ACTIVE=$(grep -oP 'server 127.0.0.1:\K\d+' /etc/nginx/conf.d/upstream.conf)
if [ "$ACTIVE" = "3001" ]; then
DEPLOY_PORT=3002
DEPLOY_ENV="green"
else
DEPLOY_PORT=3001
DEPLOY_ENV="blue"
fi
echo "Deploying to $DEPLOY_ENV (port $DEPLOY_PORT)..."
# Deploy new version
cd /var/www/$DEPLOY_ENV
git pull
npm ci --production
npm run build
pm2 restart $DEPLOY_ENV
# Wait for health check
sleep 5
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:$DEPLOY_PORT/health)
if [ "$HTTP_CODE" != "200" ]; then
echo "Health check failed! Aborting."
exit 1
fi
# Switch traffic
sed -i "s/server 127.0.0.1:$ACTIVE/server 127.0.0.1:$DEPLOY_PORT/" /etc/nginx/conf.d/upstream.conf
sudo nginx -t && sudo nginx -s reload
echo "Switched to $DEPLOY_ENV. Old environment available for rollback."
Blue-Green vs Other Strategies
| Strategy | Downtime | Rollback Speed | Resource Cost |
|---|---|---|---|
| Blue-Green | Zero | Instant | 2x servers |
| Rolling | Zero | Slow | 1x servers |
| Canary | Zero | Fast | 1.1x servers |
| Recreate | Brief | Slow | 1x servers |
Tip Blue-green deployments are the simplest zero-downtime strategy. The trade-off is running two environments, but on a VPS this just means two process instances on different ports.