Executing Zero Downtime Docker Compose Deployments

Executing Zero Downtime Docker Compose Deployments

What You’ll Need

  • n8n Cloud or self-hosted n8n for monitoring deployments
  • Hetzner VPS or Contabo VPS for running Docker Compose
  • DigitalOcean as an alternative hosting provider
  • Docker and Docker Compose (free, open source)
  • A terminal or SSH client
  • Basic knowledge of YAML configuration
  • Git for version control

Table of Contents

Understanding Zero Downtime Deployments

I’ve been deploying containerized applications for years, and nothing is more nerve-wracking than watching your production service go dark for even thirty seconds. Zero downtime deployments eliminate that anxiety. The core idea is straightforward: you never stop your old environment while bringing up new one. Instead, you orchestrate a graceful transition where both versions coexist, traffic gradually shifts, and if something goes wrong, you’re one command away from rolling back.

This matters because every second your service is unavailable costs you users, trust, and potentially revenue. With Docker Compose and the right strategy, you can achieve this without expensive Kubernetes clusters. I routinely deploy updates to production servers running on Hetzner VPS or Contabo VPS with zero customer impact.

The challenge isn’t just containers though. You need proper load balancing, health checks that actually work, database migrations that don’t lock your tables, and a rollback plan. Throughout this guide, I’ll walk you through proven patterns I’ve used in production.

The Blue-Green Deployment Strategy

Blue-green deployment is my go-to for Docker Compose environments. Here’s the concept: you maintain two identical production environments, blue and green. At any moment, only one handles traffic. When you deploy new code, you update the idle environment, test it, then switch traffic over. If something breaks, you switch back instantly.

The beauty is simplicity. You’re not gradually replacing containers or managing complex state. You’re just flipping a switch at the load balancer level.

I use this strategy across multiple services on Hetzner VPS instances. Here’s why it’s perfect for Docker Compose:

  1. Easy to test the new environment before going live
  2. Instant rollback if issues arise
  3. No need for specialized orchestration platforms
  4. Works with standard Docker Compose without extensions

The tradeoff is you need double the infrastructure capacity, but most production setups can handle that. If you’re running on a tight budget, you can use smaller instance types for the standby environment.

Setting Up Your Docker Compose Stack

Let me show you a production-grade Docker Compose configuration that supports blue-green deployments. I’m building a typical microservices setup with a web application, database, and cache layer.

Here’s my base docker-compose.yml file:

version: '3.9'

services:
  web:
    image: myapp:${APP_VERSION}
    container_name: web_app
    ports:
      - "${WEB_PORT}:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgres://user:password@db:5432/appdb
      - REDIS_URL=redis://cache:6379
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 30s
    restart: unless-stopped
    networks:
      - app-network
    volumes:
      - ./logs:/app/logs
    deploy:
      resources:
        limits:
          cpus: '1'
          memory: 512M
        reservations:
          cpus: '0.5'
          memory: 256M

  db:
    image: postgres:15-alpine
    container_name: app_db
    environment:
      - POSTGRES_USER=appuser
      - POSTGRES_PASSWORD=securepassword123
      - POSTGRES_DB=appdb
    ports:
      - "${DB_PORT}:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./init-db.sql:/docker-entrypoint-initdb.d/init.sql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U appuser"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - app-network
    restart: unless-stopped

  cache:
    image: redis:7-alpine
    container_name: app_cache
    ports:
      - "${CACHE_PORT}:6379"
    command: redis-server --appendonly yes --requirepass redispassword123
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "--raw", "incr", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - app-network
    restart: unless-stopped

  nginx:
    image: nginx:alpine
    container_name: reverse_proxy
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./ssl:/etc/nginx/ssl:ro
      - ./logs/nginx:/var/log/nginx
    depends_on:
      - web
    networks:
      - app-network
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:

networks:
  app-network:
    driver: bridge

This configuration includes resource limits, proper health checks, and dependency ordering. The key here is that each service knows how to verify it’s ready before the next one starts.

Now, for blue-green deployments, I create separate compose files for each environment. Here’s docker-compose.blue.yml:

version: '3.9'

services:
  web:
    image: myapp:${APP_VERSION}
    container_name: web_app_blue
    ports:
      - "3001:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgres://user:password@db:5432/appdb
      - REDIS_URL=redis://cache:6379
      - ENVIRONMENT=blue
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 30s
    restart: unless-stopped
    networks:
      - app-network
    volumes:
      - ./logs/blue:/app/logs

  db:
    image: postgres:15-alpine
    container_name: app_db_blue
    environment:
      - POSTGRES_USER=appuser
      - POSTGRES_PASSWORD=securepassword123
      - POSTGRES_DB=appdb
    ports:
      - "5433:5432"
    volumes:
      - postgres_data_blue:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U appuser"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - app-network
    restart: unless-stopped

  cache:
    image: redis:7-alpine
    container_name: app_cache_blue
    ports:
      - "6380:6379"
    command: redis-server --appendonly yes --requirepass redispassword123
    volumes:
      - redis_data_blue:/data
    healthcheck:
      test: ["CMD", "redis-cli", "--raw", "incr", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - app-network
    restart: unless-stopped

volumes:
  postgres_data_blue:
  redis_data_blue:

networks:
  app-network:
    driver: bridge

And docker-compose.green.yml follows the same pattern but with green suffixes and ports 3002, 5434, and 6381.

The critical difference is port allocation. Blue runs on 3001, green on 3002. This lets both environments run simultaneously without conflicts. Your load balancer sits in front and routes traffic to whichever is active.

💡 Fast-Track Your Project: Don’t want to configure this yourself? I build custom n8n pipelines and bots. Message me with code SYS3-HUGO.

Implementing Health Checks and Readiness Probes

Health checks are non-negotiable in zero downtime deployments. Without them, your load balancer might route traffic to a container that hasn’t finished starting up yet, causing request failures.

I always implement two types of checks: startup checks that verify the service initialized, and ongoing liveness checks that confirm it’s still healthy.

Here’s a production Node.js application with comprehensive health endpoints:

const express = require('express');
const app = express();
const { Pool } = require('pg');
const redis = require('redis');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 10,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

const redisClient = redis.createClient({
  url: process.env.REDIS_URL,
});

redisClient.connect();

let startupComplete = false;
let isHealthy = true;

const initializeServices = async () => {
  try {
    const dbConnection = await pool.query('SELECT NOW()');
    console.log('Database connected:', dbConnection.rows[0]);
    
    await redisClient.ping();
    console.log('Redis connected');
    
    startupComplete = true;
  } catch (error) {
    console.error('Initialization failed:', error);
    process.exit(1);
  }
};

app.get('/health', (req, res) => {
  if (!startupComplete) {
    return res.status(503).json({ status: 'starting' });
  }
  
  if (!isHealthy) {
    return res.status(503).json({ status: 'unhealthy' });
  }
  
  res.status(200).json({ status: 'ok' });
});

app.get('/ready', (req, res) => {
  if (!startupComplete) {
    return res.status(503).json({ ready: false });
  }
  
  res.status(200).json({ ready: true });
});

app.get('/live', async (req, res) => {
  try {
    const dbCheck = await pool.query('SELECT 1');
    const redisCheck = await redisClient.ping();
    
    if (!dbCheck.rows.length || !redisCheck) {
      isHealthy = false;
      return res.status(503).json({ live: false });
    }
    
    isHealthy = true;
    res.status(200).json({ live: true });
  } catch (error) {
    isHealthy = false;
    res.status(503).json({ live: false, error: error.message });
  }
});

app.listen(3000, async () => {
  console.log('Server listening on port 3000');
  await initializeServices();
});

The health endpoint returns different statuses based on initialization state. During startup, it returns 503 (Service Unavailable). Once ready, it returns 200. This signal tells the Docker health check and load balancer whether traffic should route to this container.

For database migrations that don’t block your service, I use a separate initialization container that runs before the main app:

services:
  migrations:
    image: myapp:${APP_VERSION}
    container_name: app_migrations
    command: npm run migrate
    environment:
      - DATABASE_URL=postgres://user:password@db:5432/appdb
    depends_on:
      db:
        condition: service_healthy
    networks:
      - app-network
    restart: on-failure

  web:
    image: myapp:${APP_VERSION}
    container_name: web_app_blue
    ports:
      - "3001:3000"
    depends_on:
      migrations:
        condition: service_completed_successfully
    # ... rest of configuration

The migrations container runs before the web service starts. If migrations fail, they retry automatically. This keeps your main application container from being blocked or corrupted by incomplete schema changes.

Automating Deployments with Deployment Scripts

Manual deployments are error-prone. I always automate with scripts. Here’s my production deployment script that handles blue-green switching:

#!/bin/bash

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

CURRENT_ENV=$(cat current_env.txt 2>/dev/null || echo "blue")
NEW_ENV="green"

if [ "$CURRENT_ENV" == "green" ]; then
  NEW_ENV="blue"
fi

echo "Current environment: $CURRENT_ENV"
echo "Deploying to: $NEW_ENV"

APP_VERSION="${1:?Usage: $0 <version>}"
export APP_VERSION

echo "Building and pulling images for version $APP_VERSION..."

docker pull myapp:$APP_VERSION || {
  echo "Failed to pull image myapp:$APP_VERSION"
  exit 1
}

echo "Stopping old $NEW_ENV environment..."
docker compose -f docker-compose.${NEW_ENV}.yml down || true

sleep 2

echo "Starting new $NEW_ENV environment..."
docker compose -f docker-compose.${NEW_ENV}.yml up -d

sleep 5

echo "Waiting for services to become healthy..."

max_attempts=30
attempt=0
all_healthy=false

while [ $attempt -lt $max_attempts ]; do
  if docker compose -f docker-compose.${NEW_ENV}.yml ps | grep -q "web_app_${NEW_ENV}"; then
    if docker compose -f docker-compose.${NEW_ENV}.yml exec -T web curl -f http://localhost:3000/ready > /dev/null 2>&1; then
      all_healthy=true
      break
    fi
  fi
  
  echo "Waiting for services to be ready... (attempt $((attempt+1))/$max_attempts)"
  sleep 2
  attempt=$((attempt+1))
done

if [ "$all_healthy" = false ]; then
  echo "Services failed to become healthy. Rolling back..."
  docker compose -f docker-compose.${NEW_ENV}.yml down
  exit 1
fi

echo "Services are healthy. Switching traffic to $NEW_ENV..."

switch_traffic_to_${NEW_ENV}

echo "Verifying traffic on new environment..."

for i in {1..10}; do
  if curl -f http://localhost/health > /dev/null 2>&1; then
    echo "Traffic verification successful"
    break
  fi
  echo "Traffic verification attempt $i/10..."
  sleep 2
done

echo "Saving new current environment..."
echo "$NEW_ENV" > current_env.txt

echo "Deployment to $NEW_ENV complete. Stopping $CURRENT_ENV in background..."
docker compose -f docker-compose.${CURRENT_ENV}.yml down &

echo "Deployment successful!"

This script uses an environment file to track which version is currently active. When you run it, it deploys to the inactive environment, verifies health, switches traffic, and cleans up the old one. The deployment happens atomically from the user’s perspective.

To run this, you’d execute:

chmod +x deploy.sh
./deploy.sh v2.5.0

Load Balancing and Traffic Switching

Your load balancer is the orchestrator of zero downtime. I use Nginx for this, sitting in front of both blue and green environments. The key is using Nginx’s upstream configuration with dynamic socket rewriting.

Here’s my production nginx.conf:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
  worker_connections 1024;
}

http {
  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

  access_log /var/log/nginx/access.log main;

  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;

  gzip on;
  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_types text/plain text/css text/xml text/javascript 
             application/json application/javascript application/xml+rss 
             application/rss+xml font/truetype font/opentype 
             application/vnd.ms-fontobject image/svg+xml;

  upstream app_backend {
    least_conn;
    server web_app_blue:3000 max_fails=3 fail_timeout=30s;
    server web_app_green:3000 max_fails=3 fail_timeout=30s down;
  }

  server {
    listen 80;
    server_name _;

    client_max_body_size 50M;

    location / {
      proxy_pass http://app_backend;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_cache_bypass $http_upgrade;
      proxy_connect_timeout 60s;
      proxy_send_timeout 60s;
      proxy_read_timeout 60s;
    }

    location /health {
      proxy_pass http://app_backend;
      access_log off;
    }
  }
}

Notice the upstream app_backend block. I mark green as down initially, so all traffic goes to blue. When you’re ready to switch, you reload Nginx with an updated config that marks blue as down and green as active.

Here’s the function that switches traffic:

switch_traffic_to_blue() {
  sed -i 's/server web_app_blue:3000 max_fails=3 fail_timeout=30s;/server web_app_blue:3000 max_fails=3 fail_timeout=30s;/g' nginx.conf
  sed -i 's/server web_app_green:3000 max_fails=3 fail_timeout=30s down;/server web_app_green:3000 max_fails=3 fail_timeout=30s down;/g' nginx.conf
  sed -i 's/server web_app_blue:3000 max_fails=3 fail_timeout=30s;/server web_app_blue:3000 max_fails=3 fail_timeout=30s;/g' nginx.conf
  sed -i 's/server web_app_green:3000 max_fails=3 fail_timeout=30s down;/server web_app_green:3000 max_fails=3 fail_timeout=30s down;/g' nginx.conf
  
  docker exec reverse_proxy nginx -s reload
}

switch_traffic_to_green() {
  sed -i 's/server web_app_blue:3000 max_fails=3 fail_timeout=30s;/server web_app_blue:3000 max_fails=3 fail_timeout=30s down;/g' nginx.conf
  sed -i 's/server web_app_green:3000 max_fails=3 fail_timeout=30s down;/server web_app_green:3000 max_fails=3 fail_timeout=30s;/g' nginx.conf
  
  docker exec reverse_proxy nginx -s reload
}

The nginx -s reload command reloads the configuration without dropping existing connections. This is a graceful switch that takes milliseconds.

For applications that handle sensitive operations, you might want connection draining. Here’s an enhanced approach using a drain endpoint:

drain_connections_from_blue() {
  echo "Draining connections from blue environment..."
  
  docker exec reverse_proxy bash -c 'sed -i "s/server web_app_blue:3000/server web_app_blue:3000 drain/g" /etc/nginx/nginx.conf'
  docker exec reverse_proxy nginx -s reload
  
  for i in {1..60}; do
    connection_count=$(curl -s http://localhost:3001/connections || echo "0")
    if [ "$connection_count" -eq 0 ]; then
      echo "All connections drained"
      return 0
    fi
    echo "Waiting for connections to drain... ($connection_count remaining)"
    sleep 1
  done
  
  echo "Timeout waiting for connections to drain"
  return 1
}

If you’re deploying frequently and need automated monitoring of these transitions, n8n Cloud can orchestrate your deployment workflow and send notifications on failures. I’ve built deployment pipelines that trigger tests, check logs, and rollback automatically.

Monitoring and Rollback Procedures

Monitoring during deployments is critical. I track container health, traffic patterns, error rates, and resource usage in real time.

Here’s a monitoring script that checks both environments:

#!/bin/bash

echo "=== Deployment Health Report ==="
echo ""
echo "Blue Environment:"
docker compose -f docker-compose.blue.yml ps
docker compose -f docker-compose.blue.yml exec -T web curl -s http://localhost:3000/health | jq '.' 2>/dev/null || echo "Unhealthy or unreachable"
echo ""
echo "Green Environment:"
docker compose -f docker-compose.green.yml ps
docker compose -f docker-compose.green.yml exec -T web curl -s http://localhost:3000/health | jq '.' 2>/dev/null || echo "Unhealthy or unreachable"
echo ""
echo "Nginx Status:"
docker exec reverse_proxy nginx -T 2>/dev/null | grep "upstream" -A 5
echo ""
echo "Recent Nginx Access Logs:"
docker exec reverse_proxy tail -20 /var/log/nginx/access.log | awk '{print $9}' | sort | uniq -c | sort -rn
echo ""
echo "Current Environment: $(cat current_env.txt)"

For rollback, the process is simple but should be automated:

#!/bin/bash

echo "Rolling back to previous environment..."

CURRENT_ENV=$(cat current_env.txt)
PREVIOUS_ENV="green"

if [ "$CURRENT_ENV" == "green" ]; then
  PREVIOUS_ENV="blue"
fi

echo "Switching traffic back to $PREVIOUS_ENV..."

switch_traffic_to_${PREVIOUS_ENV}

sleep 3

echo "Verifying traffic on rollback environment..."
if curl -f http://localhost/health > /dev/null 2>&1; then
  echo "Rollback successful"
  echo "$PREVIOUS_ENV" > current_env.txt
  
  echo "Stopping failed $CURRENT_ENV environment..."
  docker compose -f docker-compose.${CURRENT_ENV}.yml down
else
  echo "Rollback verification failed!"
  exit 1
fi

For comprehensive deployment monitoring, particularly when managing logs across both environments, refer to Setting Up Logrotate for Custom Linux Server Logs. This prevents your log volumes from ballooning during the deployment process.

If your application serves dynamic content or makes external API calls, consider Extracting Dynamic JavaScript Content Using Headless Browsers in your health checks to verify the full request pipeline works.

For security-sensitive deployments where webhooks are involved, review Securing Webhook Endpoints with Nginx Reverse Proxy to ensure your blue and green environments both validate incoming requests properly.

Getting Started

You’re ready to implement zero downtime deployments right now. Here’s the checklist:

  1. Set up your infrastructure on Hetzner VPS, Contabo VPS, or DigitalOcean
  2. Install Docker and Docker Compose (versions 20.10+ recommended)
  3. Create your base docker-compose.yml with proper health checks
  4. Create docker-compose.blue.yml and docker-compose.green.yml with different ports
  5. Configure Nginx with upstream groups
  6. Test the deployment script in staging first
  7. Run your first production deployment with confidence

The infrastructure cost is minimal if you’re already running production containers. If you’re on a budget, your blue and green environments can share the same database and cache, reducing memory overhead significantly. Just ensure they have separate application containers.

Outsource Your Automation

Don’t have time? I build production n8n workflows, WhatsApp bots, and fully automated YouTube Shorts pipelines. Hire me on Fiverr, mention SYS3-HUGO for priority. Or DM at chasebot.online.

Zero downtime deployments eliminate deployment anxiety. With Docker Compose, Nginx, and the strategies I’ve shared, you can push updates to production without users noticing. Start with a staging environment to test the flow, document your rollback procedures, and you’re golden. Your deployment process goes from risky event to routine operation.

Want to automate this yourself?

Start with n8n Cloud (free tier available) or self-host on a Hetzner VPS for full control.

Want this engine running on your own VPS?

This blog publishes itself — daily, unattended, on free API tiers. The full engine, Hugo theme, and setup guide are available as System 3.

Get System 3
system online