Updated 6 min read
Blue-green deploys with Docker and nginx
Ship a new version without dropping requests on one server: readiness checks, smoke tests, a graceful nginx switch, SIGTERM handling and instant rollback.
A green CI pipeline tells you the code is tested, built and scanned. It says nothing about what your users experience while the new version replaces the old one. If deploying means docker stop followed by docker run, every request that arrives in between fails — and if the new version crashes on start, you are down until someone fixes it.
Blue-green deployment avoids both problems with one idea: start the new version next to the old one, prove it works, then move the traffic. You don’t need Kubernetes for that. A single VPS with Docker and nginx is enough — with limits we’ll be honest about at the end.
Advertisement
The setup
┌────────────── nginx :80 ──────────────┐
│ upstream → 127.0.0.1:3001 (blue) │
└──────────────────┬────────────────────┘
│
┌───────────────────────┴───────────────────────┐
blue :3001 (v1, live) green :3002 (v2, starting)
Two “colors”, each a container on its own local port. nginx sends all traffic to one of them. The containers only listen on 127.0.0.1; nginx is the only thing exposed.
The upstream address lives in its own one-line file, so a deploy script can rewrite it without touching the rest of the nginx configuration:
# /etc/nginx/conf.d/orders-api.conf
upstream orders_api {
include /etc/nginx/orders-api-upstream.conf; # "server 127.0.0.1:3001;"
keepalive 16;
}
server {
listen 80 default_server;
location / {
proxy_pass http://orders_api;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Two health endpoints, not one
The application exposes two endpoints, and they answer different questions:
/healthz— liveness: is the process up? It also returns the version (the commit SHA baked into the image), which turns out to be very useful./readyz— readiness: may this instance receive traffic right now? It returns503as soon as shutdown begins (before the server is listening, nothing answers at all, which a checker treats the same way). In a real service it would also check critical dependencies such as the database.
if (req.method === "GET" && pathname === "/healthz") {
return send(res, 200, { status: "ok", version: state.version });
}
if (req.method === "GET" && pathname === "/readyz") {
return state.ready ? send(res, 200, { status: "ready" }) : send(res, 503, { status: "not ready" });
}
A process can be alive but not ready — still warming up, or draining before it exits. Collapsing both into one endpoint is how deployments send traffic to instances that cannot serve it.
The deployment, step by step
The deploy script takes one argument: the image by digest (ghcr.io/owner/app@sha256:…), never a tag. Here is what it does, with the escape route at every step.
1. Refuse mutable references
[[ "$IMAGE_REF" == *@sha256:* ]] || { log "refusing mutable reference: $IMAGE_REF"; exit 2; }
The CI pipeline scanned one exact image. Deploying anything else defeats the point.
2. Start the idle color
active=$(cat "$BASE/active" 2>/dev/null || echo green)
if [[ $active == blue ]]; then next=green; else next=blue; fi
# The idle color still runs the release before last: stop it gracefully first.
docker stop --time 30 "$APP-$next" > /dev/null 2>&1 || true
docker rm "$APP-$next" > /dev/null 2>&1 || true
docker run --detach --name "$APP-$next" --init --restart unless-stopped \
--env-file "$BASE/app.env" \
--publish "127.0.0.1:${PORT[$next]}:3000" \
--stop-timeout 30 \
"$IMAGE_REF"
The live version is untouched. --init gives the container a minimal init process so signals are forwarded and zombie processes reaped.
3. Wait for readiness
for _ in $(seq 1 30); do
if curl -fsS "http://127.0.0.1:$port/readyz" > /dev/null 2>&1; then ready=yes; break; fi
sleep 2
done
[[ $ready == yes ]] || fail "$next never became ready"
If the new version never becomes ready — a missing environment variable, a crash on start — the script removes it and exits. Traffic never left the old version. Users noticed nothing.
4. Smoke-test it directly
Before any real user reaches it, the script calls the new instance on its private port: health, readiness, and one real business request with a known answer.
body='{"items":[{"sku":"SMOKE-1","quantity":2,"unitPriceCents":1000}]}'
curl -fsS -H 'content-type: application/json' -d "$body" "$base/v1/invoices/preview" \
| grep -q '"totalCents":2380'
A readiness check proves the server answers. A smoke test proves it answers correctly.
5. Switch the traffic
printf 'server 127.0.0.1:%s;\n' "${PORT[$next]}" > "$UPSTREAM.tmp"
mv "$UPSTREAM.tmp" "$UPSTREAM"
nginx -t -q && nginx -s reload
Writing to a temporary file and renaming it makes the change atomic. nginx -t validates the configuration first; if it fails, the script restores the previous file.
nginx -s reload is what makes the switch seamless. As the nginx documentation describes, the master process starts new worker processes with the new configuration, and the old workers stop accepting connections but finish the requests they are already serving before exiting. No request is cut off mid-flight.
6. Verify through the proxy
expected=$(docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$APP-$next" \
| sed -n 's/^APP_VERSION=//p')
served=$(curl -fsS http://127.0.0.1/healthz | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')
[[ "$served" == "$expected" ]] || { switch_to "$active"; fail "post-switch verification failed"; }
This is where the version in /healthz pays off: the script asks nginx — the same path real users take — which version answers. If it is not the one just deployed, the script switches back automatically.
7. Keep the old color running
The previous version stays up, idle. A rollback is a single reload:
switch_to "$previous" # rewrite the upstream, nginx -s reload
It only works if the previous container still answers on /readyz; otherwise you redeploy a known-good digest. The old color is stopped cleanly at the start of the next deployment.
Graceful shutdown: the other half
Moving traffic away gracefully is useless if the old process dies abruptly. When Docker stops a container it sends SIGTERM, waits for the stop timeout, then sends SIGKILL. The application has to use that window:
function shutdown(signal: NodeJS.Signals) {
if (shuttingDown) return;
shuttingDown = true;
state.ready = false; // 1. fail readiness
server.close((error) => process.exit(error ? 1 : 0)); // 2. finish in-flight requests
setTimeout(() => process.exit(1), config.shutdownTimeoutMs).unref(); // 3. never hang
}
process.on("SIGTERM", shutdown);
Three steps, in order: stop advertising readiness, stop accepting connections while letting in-flight requests complete, and exit on your own before the orchestrator kills you.
Be clear about what the first step buys you. Here the readiness flip and server.close() happen back to back, which is fine for this setup: by the time Docker stops the old color, nginx has already been switched away from it. Behind a load balancer that polls /readyz, you would add a short delay between the two (a few seconds, longer than the polling interval) so the balancer notices before the server stops accepting connections. Keep the application’s own timeout (20 seconds here) below Docker’s --stop-timeout (30 seconds), so the process always exits by itself.
Two details make this work. The image’s CMD uses the exec form — CMD ["node", "dist/server.js"] — so Node receives the signal directly instead of a shell swallowing it. And since Node 19, server.close() also closes idle keep-alive connections, which used to keep processes alive long after the last real request.
The database is shared
During the switch, and for as long as you keep the old color for rollback, two versions run against the same database. A migration that renames or drops a column will break the version still serving — the deployment “succeeds”, then the old version fails during the switch or, worse, the moment you roll back.
The fix is the expand → migrate → contract pattern (also called parallel change):
- Expand — add the new column alongside the old one; the new version writes to both.
- Migrate — backfill old rows; the next version reads the new column.
- Contract — once no running version reads the old column, drop it, in a separate release.
What a single server cannot do
Be honest about the limits:
- It is not high availability. If the machine reboots or fails, the service is down. Real redundancy needs several hosts behind a load balancer.
- Both versions run during the switch, so the server needs headroom for twice the memory and CPU for a short time.
- Long-lived connections such as WebSockets keep old nginx workers alive until they close; plan for reconnects.
Within those limits, the result is a deployment that either succeeds without users noticing, or fails without users noticing — which is the whole goal.