DevOps

Zero-Downtime Blue-Green Docker Deploys on $20 VPS: Automating Rollbacks with Caddy and Compose Under Flaky Bandwidth

C
Chidi OkekeVP of Frontend Engineering
November 7, 202612 min read
Zero-Downtime Blue-Green Docker Deploys on $20 VPS: Automating Rollbacks with Caddy and Compose Under Flaky Bandwidth

Partial Docker layer pulls mid-deployment often break live containers during bandwidth drops. Here is how we automated atomic blue-green deploys and rollbacks on single-node VPS setups using Docker Compose, Caddy's API, and shell scripts.

It was 4:30 PM on a Thursday in Lagos when a route flap on the MainOne submarine cable spiked packet loss across local ISPs to 35%. Right at that exact second, a developer pushed a fix to main. The GitHub Actions runner connected to our $20 staging VPS, initiated docker compose up -d --build, and started pulling missing base layers from Docker Hub.

Then the connection stalled. Docker pulled three out of six layers, hit an read timeout, and terminated. Because Docker Compose had already stopped the old running container to recreate the network bindings, the application was left in a dead state. Caddy threw immediate 502 Bad Gateway errors to hundreds of active shoppers. The deployment wasn't atomic. A standard Docker deploy stopped the working system before confirming the new image was entirely pulled and healthy.

When operating on budget virtual private servers with international transit paths that occasionally drop packets, default deployment strategies fail. You cannot rely on zero-downtime rolling updates native to Kubernetes when running single-node architectures to control infrastructure costs—a trade-off we previously analyzed in our guide on AWS EKS to $140/mo Hetzner Bare Metal: Slashing SaaS Infrastructure Costs by 73% for a Nigerian Logistics Engine.

Here is how we solved this: an atomic blue-green deployment harness built directly on single-node VPS instances using Docker Compose, Caddy's dynamic admin API, and a resilience-focused Bash orchestrator.

Diagram showing Blue-Green Docker container routing via Caddy API dynamic upstream proxying

The Architecture: Dual Sockets and Dynamic Proxying

To achieve true zero-downtime on a single host without multi-node orchestrators, we run two distinct instances of the application backend simultaneously on different local ports (e.g., port 8001 for Blue and port 8002 for Green).

Instead of letting Docker expose ports directly to the public network, we put Caddy Web Server in front. Caddy maintains the public SSL termination and acts as a dynamic reverse proxy. When a deployment starts, the script builds or pulls the idle environment completely. If the image pull fails mid-way due to network drops, the active environment continues serving traffic without interruption.

Only after the new container passes HTTP health checks does the deployment script instruct Caddy via its HTTP REST API to swap upstream targets. The shift happens in under 5 milliseconds with zero dropped connections.

Here is the target directory structure on the target deployment server:

/opt/app/
├── Caddyfile
├── docker-compose.blue.yml
├── docker-compose.green.yml
├── deploy.sh
└── active_env

Step 1: Defining Blue and Green Compose Files

Create two separate Compose files. Notice how neither binds directly to 0.0.0.0:80 or 0.0.0.0:443. They only expose their respective internal ports on 127.0.0.1.

Here is docker-compose.blue.yml:

version: '3.8'

services:
  web_blue:
    image: myregistry.azurecr.io/api:latest
    container_name: app_blue
    restart: always
    environment:
      - PORT=8001
      - ENVIRONMENT=blue
    ports:
      - "127.0.0.1:8001:8001"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8001/healthz"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 10s

And the matching docker-compose.green.yml:

version: '3.8'

services:
  web_green:
    image: myregistry.azurecr.io/api:latest
    container_name: app_green
    restart: always
    environment:
      - PORT=8002
      - ENVIRONMENT=green
    ports:
      - "127.0.0.1:8002:8002"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8002/healthz"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 10s

Step 2: Provisioning Caddy with Admin API Enabled

Caddy allows live configuration changes without reloading the binary or breaking TCP sockets. We configure our initial Caddyfile with an explicit @id marker on our proxy handler so we can mutate it on the fly via JSON patches.

{
    admin 127.0.0.1:2019
}

api.yourdomain.com {
    reverse_proxy @service_upstream 127.0.0.1:8001 {
        header_up Host {upstream_hostport}
    }
}

When Caddy starts, port 8001 (Blue) serves all public requests.

The Zero-Downtime Deployment Orchestrator

Now we write deploy.sh. This script handles layer pulling, robust retries for unstable connections, health checking, Caddy hot-swapping, and immediate cleanup. It takes zero risks: if any step fails, it exits before touching the live service.

#!/usr/bin/env bash
set -euo pipefail

APP_DIR="/opt/app"
CADDY_API="http://127.0.0.1:2019"
ACTIVE_FILE="$APP_DIR/active_env"

# Read current active environment; default to blue
if [ -f "$ACTIVE_FILE" ]; then
    CURRENT_COLOR=$(cat "$ACTIVE_FILE")
else
    CURRENT_COLOR="blue"
fi

if [ "$CURRENT_COLOR" == "blue" ]; then
    NEW_COLOR="green"
    NEW_PORT="8002"
    OLD_PORT="8001"
    NEW_COMPOSE="docker-compose.green.yml"
    OLD_COMPOSE="docker-compose.blue.yml"
else
    NEW_COLOR="blue"
    NEW_PORT="8001"
    OLD_PORT="8002"
    NEW_COMPOSE="docker-compose.blue.yml"
    OLD_COMPOSE="docker-compose.green.yml"
fi

echo "==> Current active deployment: $CURRENT_COLOR (port $OLD_PORT)"
echo "==> Target target deployment: $NEW_COLOR (port $NEW_PORT)"

# Step 1: Pull images with retries (critical over flaky African international transit)
MAX_RETRIES=5
RETRY_COUNT=0
echo "==> Pulling latest images for $NEW_COLOR..."

until docker compose -f "$APP_DIR/$NEW_COMPOSE" pull; do
    RETRY_COUNT=$((RETRY_COUNT+1))
    if [ $RETRY_COUNT -ge $MAX_RETRIES ]; then
        echo "[ERROR] Failed to pull Docker image after $MAX_RETRIES attempts. Aborting deploy."
        exit 1
    fi
    echo "[WARN] Network error during pull. Retrying ($RETRY_COUNT/$MAX_RETRIES) in 5 seconds..."
    sleep 5
done

# Step 2: Boot new environment containers
echo "==> Starting $NEW_COLOR environment..."
docker compose -f "$APP_DIR/$NEW_COMPOSE" up -d

# Step 3: Health check validation loop
echo "==> Waiting for $NEW_COLOR container on port $NEW_PORT to become healthy..."
HEALTH_CHECKS=0
MAX_HEALTH_CHECKS=12
IS_HEALTHY=false

while [ $HEALTH_CHECKS -lt $MAX_HEALTH_CHECKS ]; do
    HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:${NEW_PORT}/healthz" || true)
    if [ "$HTTP_STATUS" == "200" ]; then
        IS_HEALTHY=true
        break
    fi
    echo "Health check returned status $HTTP_STATUS. Retrying in 5s... ($((HEALTH_CHECKS+1))/$MAX_HEALTH_CHECKS)"
    HEALTH_CHECKS=$((HEALTH_CHECKS+1))
    sleep 5
done

if [ "$IS_HEALTHY" = false ]; then
    echo "[FATAL] $NEW_COLOR service failed health checks! Rolling back."
    docker compose -f "$APP_DIR/$NEW_COMPOSE" stop
    exit 1
fi

# Step 4: Hot-swap upstream proxy target in Caddy via REST API
echo "==> Swapping proxy upstream target to 127.0.0.1:$NEW_PORT..."

# Update Caddy reverse proxy upstream via patch
PATCH_PAYLOAD=$(cat <<EOF
[
  {
    "op": "replace",
    "path": "/apps/http/servers/srv0/routes/0/handle/0/routes/0/handle/0/upstreams/0/dial",
    "value": "127.0.0.1:${NEW_PORT}"
  }
]
EOF
)

# If using standard JSON config path in Caddy:
curl -X PATCH "$CADDY_API/config/"
  -H "Content-Type: application/json" \
  -d "$PATCH_PAYLOAD"

echo "$NEW_COLOR" > "$ACTIVE_FILE"
echo "==> Hot-swap complete. Active environment is now $NEW_COLOR."

# Step 5: Gracefully shut down old environment
echo "==> Stopping old $CURRENT_COLOR environment..."
sleep 5 # Brief pause to finish inflight requests
docker compose -f "$APP_DIR/$OLD_COMPOSE" stop
echo "==> Deployment successfully finished."

Make the script executable:

chmod +x /opt/app/deploy.sh

Optimizing GitHub Actions for Flaky Remote Execution

Triggering remote Docker deployments over SSH via GitHub Actions often leads to broken pipelines if the runner drops its TCP socket mid-execution. Similar to how we handle external network drops in our guide on Handling 504 Gateway Timeouts from NIMC: Building a Resilient BVN/NIN Verification Pipeline in Go, your CI engine must handle transient connection resets gracefully.

Below is a GitHub Actions workflow that builds images remotely, pushes them to a registry with chunked upload retries, and executes the target deployment script via an SSH session wrapped in connection timeout checks.

name: Production Deployment

on:
  push:
    branches:
      - main

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: myregistry.azurecr.io
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: myregistry.azurecr.io/api:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Execute Blue-Green Deploy on Remote Host
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ secrets.SERVER_IP }}
          username: root
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          command_timeout: 15m
          script: |
            /opt/app/deploy.sh

Performance and Reliability Comparison

Here is how this single-node Blue-Green setup performs compared to conventional deployment techniques on low-cost virtual private servers over unreliable network connections.

| Deployment Strategy | Downtime During Push | Resistance to Network Drops | Memory Overhead | Complexity | | :--- | :--- | :--- | :--- | :--- |: | Standard docker compose up | 5s – 120s | Low (Container stopped before pull) | Minimal | Low | | docker compose up --build | 30s – 300s | Extremely Low (High risk of mid-build failure) | Medium | Low | | Caddy + Docker Blue-Green | 0ms | High (Fails safely without touching live environment) | 2x (During brief deployment swap) | Medium | | Kubernetes (k3s/MicroK8s) | 0ms | High | High (Unsuitable for 1GB-2GB RAM VPS) | Very High |

Common Pitfalls

1. Host Memory Exhaustion During Dual Container Spikes

Running both Blue and Green containers simultaneously means your VPS memory usage doubles during the 30-second deployment window. If your host has 2GB of RAM and your container uses 1.2GB, Linux's Out-Of-Memory (OOM) killer will kill your active container during the up -d step.

Solution: Add strict memory limits inside your Compose files (mem_limit: 800m) and create a 2GB swap file on the host operating system using fallocate or dd. Swap is slow, but it prevents OOM crashes during the transient 10-second window when both Blue and Green containers run simultaneously.

2. Orphaned Docker Volumes and Layer Disk Bloat

Building or pulling images repeatedly without cleaning up dangling objects will fill a 40GB SSD within two weeks, causing deployments to crash due to No space left on device errors.

Solution: Append a garbage collection step to your cron jobs or deployment script:

# Remove images older than 72 hours without destroying named volumes
docker image prune -a --force --filter 

Neobot Engineering Standard

Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.

Tags:#DevOps#Docker#Caddy#CI/CD#Infrastructure#Linux

Discussion

Comments Coming Soon

We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.