Lab: blue-green cutover and rollback behind the proxy
Run a blue-green traffic cutover behind an Nginx reverse proxy, validate target stack health, and let a watch script roll back automatically when the new stack returns errors.
Contentsand lesson path
On this page
- Blue-Green Architecture: Two Environments and a Fast Switch
- Automated Cutover and Metric-Driven Fast Rollback
- Lab Execution: Cutover, Synthetic Failure, and Fast Rollback
- Check your understanding
- Apply it
- Review prompt
Lessons of CD Strategies
- Delivery, deployment and rollout strategies: how each one fails Concept · 25 min
- Lab: a staged pipeline with approval and smoke tests Lab · 30 min
- Lab: a TLS-terminating reverse proxy in front of the service Lab · 30 min
- Lab: blue-green cutover and rollback behind the proxy Lab · 25 min
- Schema changes, feature flags, GitOps, traffic splitting and service meshes Concept · 30 min
- Check: choose and defend a release plan Knowledge check · 10 questions
What you will learn
- Define rollback criteria from health checks and error rates, keep schema changes backward compatible, and execute a rollback within a target time.
- Configure a reverse proxy such as Nginx to route by host and path, terminate TLS with an automatically renewed ACME certificate, pass forwarded headers and sane timeouts, and switch traffic between two upstream releases.
Prerequisites: Cloud Basics, Continuous Integration
01. Blue-Green Architecture: Two Environments and a Fast Switch
A rolling update has a weak spot: while it moves across a fleet, which can take many minutes on a large one, the old version (v1) and the new version (v2) run side by side. If a serious bug or a database incompatibility shows up halfway through, reversing the rollout is another rolling replacement that takes about as long again, and users keep hitting the bad version meanwhile.
The Blue-Green Deployment pattern shortens that rollback to a proxy switch by running two complete, identical production environments:
-
Blue Environment (Active): Currently hosts the live production release (
v2.3.9) and receives all user requests through the reverse proxy. -
Green Environment (Idle): Hosts the new release candidate (
v2.4.0). It receives no user traffic yet, but it is a full production copy, connected to the real backend services and ready to take traffic. -
The Cutover: Once Green has warmed up and passed its smoke tests, a deployment step points the reverse proxy's upstream at Green and reloads it. In Nginx, a reload (
nginx -s reload) starts new worker processes with the new configuration, and the old workers stop accepting new connections and finish the requests they are already serving, so ordinary HTTP requests are not dropped. Idle keep-alive client connections are closed (clients simply reconnect), and long-lived connections such as WebSockets or streams stay on the old worker, and the old upstream, until they close orworker_shutdown_timeoutexpires. New requests go to Green within about a second.
Because the Blue environment stays running and warm beside Green, rollback is not a redeployment; it is simply pointing the proxy back to Blue and reloading, which takes about a second once someone, or something, has decided to roll back. That holds only while Blue still works with the shared database, so Green must not have made schema or data changes that Blue cannot handle.
You can also switch at the DNS level (for example by changing a Route 53 record) instead of at a proxy. That avoids running a proxy, but it suffers from DNS caching and TTL lag. Some resolvers, corporate proxies and client applications ignore low TTL values (e.g. 5 seconds) and keep old answers for minutes or longer. During a DNS-based cutover or emergency rollback, traffic keeps trickling into the failing environment for as long as those caches hold the old record. In contrast, a proxy-based cutover sends every new request to the new stack as soon as the reload completes; only connections that were already open finish on the old one.
02. Automated Cutover and Metric-Driven Fast Rollback
A production blue-green cutover has three stages:
-
Check Green before the switch: a script sends test requests straight to Green (
http://127.0.0.1:8082/healthz) and checks that it answers, that its database and cache connections work, and that the responses have the expected JSON shape. -
Switch the upstream: in Nginx, point a symlink or an included file (
upstream.conf) at Green, check the syntax withnginx -tand runnginx -s reload. -
Watch, and roll back automatically: after the switch, a monitor watches the error rate and latency over an evaluation window, for example 5 minutes. If the share of 5xx responses rises above a set limit (for example 1%) or p99 latency above 2 seconds, it switches back to Blue without waiting for a person.
The lab below wires these three stages together on one machine.
03. Lab Execution: Cutover, Synthetic Failure, and Fast Rollback
You will run two versions of a tiny service side by side, put Nginx in front of them, switch traffic from Blue to Green, inject errors into Green and let a watch script roll back to Blue. Everything runs as your own user on 127.0.0.1.
What you need: Python 3.11 or later, curl, Bash and Nginx 1.19.5 or later (for the -e flag; on Debian or Ubuntu sudo apt install nginx, on macOS brew install nginx). Stop any system Nginx that already listens on port 8080. Create a directory bluegreen-lab/ with these files: backend.py, nginx.conf, blue.conf, green.conf, cutover.sh, watch.sh, and run chmod +x *.sh.
- The backends. One script serves both stacks.
FAIL_EVERY=10makes every tenth ordinary request return HTTP 500 while/healthzstays healthy, which is how many real bugs look.
"""Blue or green backend. Usage: VERSION=v2.4.0 PORT=8082 python3 backend.py"""
import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = os.environ.get("VERSION", "dev")
FAIL_EVERY = int(os.environ.get("FAIL_EVERY", "0")) # 10 = every 10th request
count = 0
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1" # allow keep-alive from the proxy
def do_GET(self):
global count
status, body = 200, {"version": VERSION}
if self.path != "/healthz":
count += 1
if FAIL_EVERY and count % FAIL_EVERY == 0:
status, body = 500, {"version": VERSION, "error": "injected"}
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args):
pass
port = int(os.environ.get("PORT", "8081"))
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()- The proxy configuration.
nginx.confincludesactive.conf, a symlink to eitherblue.conforgreen.conf; both define the same upstream name,active_backend. The temp paths and the-pprefix let Nginx run without root. Before Nginx 1.29.7,keepalivein the upstream only takes effect together withproxy_http_version 1.1and an emptyConnectionheader, as set in thelocation; from 1.29.7 those are the defaults, and setting them explicitly works on every version.
# Run as an ordinary user from this directory (see step 2).
worker_processes 1;
pid nginx.pid;
error_log logs/error.log;
events { worker_connections 256; }
http {
access_log logs/access.log;
client_body_temp_path tmp/body;
proxy_temp_path tmp/proxy;
fastcgi_temp_path tmp/fastcgi;
uwsgi_temp_path tmp/uwsgi;
scgi_temp_path tmp/scgi;
include active.conf; # symlink to blue.conf or green.conf
server {
listen 127.0.0.1:8080;
location / {
proxy_pass http://active_backend;
proxy_http_version 1.1; # needed for upstream keep-alive
proxy_set_header Connection ""; # needed for upstream keep-alive
proxy_set_header Host $host;
}
}
}# Blue: the current release
upstream active_backend {
server 127.0.0.1:8081;
keepalive 16;
}# Green: the new release
upstream active_backend {
server 127.0.0.1:8082;
keepalive 16;
}- The cutover and watch scripts.
cutover.shswaps the symlink, tests the configuration withnginx -tand reloads; if the test fails it puts the old symlink back.nginx -s reloadreturns as soon as it has signalled the master process, before the new worker has taken over. The master starts the new worker first and only then tells the old one to finish, so the script waits (at most 10 seconds) until the old worker process has exited before it reports the switch.watch.shsends a window of requests through the proxy, computes the share of 5xx responses and callscutover.sh bluewhen the share is above the limit.
#!/usr/bin/env bash
# Usage: ./cutover.sh blue|green - point the proxy at one stack and reload.
set -euo pipefail
cd "$(dirname "$0")"
TARGET="${1:?usage: cutover.sh blue|green}"
[[ -f "${TARGET}.conf" ]] || { echo "unknown stack: ${TARGET}" >&2; exit 1; }
NGINX=(nginx -p "${PWD}/" -c "${PWD}/nginx.conf" -e "${PWD}/logs/error.log")
PREVIOUS="$(readlink active.conf)"
ln -sfn "${TARGET}.conf" active.conf
if ! "${NGINX[@]}" -t -q; then
ln -sfn "${PREVIOUS}" active.conf # keep the old target if the config is bad
echo "config test failed; still on ${PREVIOUS%.conf}" >&2
exit 1
fi
OLD="$(pgrep -P "$(cat nginx.pid)")" # the worker that serves now
"${NGINX[@]}" -s reload
for _ in $(seq 50); do # wait up to 10 s for the old worker to exit
kill -0 "${OLD}" 2> /dev/null || break; sleep 0.2
done
echo "cutover: ${PREVIOUS%.conf} -> ${TARGET}"#!/usr/bin/env bash
# Usage: ./watch.sh <requests> <max-error-percent>
# Sends requests through the proxy; rolls back to blue if 5xx share is too high.
set -euo pipefail
cd "$(dirname "$0")"
TOTAL="${1:-50}"; MAX_PCT="${2:-1}"; ERRORS=0
URL="${URL:-http://127.0.0.1:8080/}" # the proxy
for _ in $(seq 1 "${TOTAL}"); do
CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 "${URL}" || true)
if [[ "${CODE}" == 5* || "${CODE}" == 000 ]]; then ERRORS=$((ERRORS + 1)); fi
done
PCT=$((100 * ERRORS / TOTAL))
echo "window: ${TOTAL} requests, ${ERRORS} errors (${PCT}%), limit ${MAX_PCT}%"
if (( PCT > MAX_PCT )); then
echo "error budget exceeded: rolling back to blue"
./cutover.sh blue
fi- Start both stacks and the proxy, with Blue active. A Python server needs a moment before it listens, so
wait_healthyasks each backend's health check every 0.2 seconds, for about 10 seconds, and Nginx starts only when both have answered; without the wait, the first request can reach Nginx before Blue is up and return502 Bad Gateway. If a backend does not start (for example because its port is taken), you get a message after about 10 seconds instead of a shell that waits forever. The proxy then answers with Blue's version, and Green answers its health check directly. Your shell also prints a job number and process ID such as[1] 48213for each&; those lines are left out below.
mkdir -p logs tmp && ln -sfn blue.conf active.conf
VERSION=v2.3.9 PORT=8081 python3 backend.py &
VERSION=v2.4.0 PORT=8082 FAIL_EVERY=10 python3 backend.py &
wait_healthy() { # ask a backend's /healthz every 0.2 s, for about 10 s
for _ in $(seq 50); do
curl -sf --max-time 1 "http://127.0.0.1:$1/healthz" > /dev/null && return 0
sleep 0.2
done
echo "backend on port $1 is not healthy after about 10 s" >&2; return 1
}
wait_healthy 8081 && wait_healthy 8082 &&
nginx -p "$PWD/" -c "$PWD/nginx.conf" -e "$PWD/logs/error.log"
curl -s http://127.0.0.1:8080/; echo
curl -s http://127.0.0.1:8082/healthz; echo{"version": "v2.3.9"}
{"version": "v2.4.0"}- Cut over to Green. The reload starts new workers with the new configuration; old workers finish the requests they are serving and then exit.
./cutover.sh green
for i in 1 2 3; do curl -s http://127.0.0.1:8080/; echo; donecutover: blue -> green
{"version": "v2.4.0"}
{"version": "v2.4.0"}
{"version": "v2.4.0"}- Let the watch script detect the errors and roll back. Green fails 10% of requests, above the 1% limit.
./watch.sh 50 1
readlink active.conf
curl -s http://127.0.0.1:8080/; echowindow: 50 requests, 5 errors (10%), limit 1%
error budget exceeded: rolling back to blue
cutover: green -> blue
blue.conf
{"version": "v2.3.9"}- A broken configuration must not take the proxy down. Save a copy of
green.conf, break the original (a missing semicolon) and try to cut over. The test fails, the symlink is restored and Nginx keeps serving Blue. The last command puts the workinggreen.confback.
cp green.conf green.conf.good # keep the working version
printf 'upstream active_backend {\n server 127.0.0.1:8082\n}\n' > green.conf
./cutover.sh green; echo "exit: $?"
readlink active.conf
mv green.conf.good green.conf # restore the working green.confnginx: [emerg] unexpected "}" in .../bluegreen-lab/active.conf:3
nginx: configuration file .../bluegreen-lab/nginx.conf test failed
config test failed; still on blue
exit: 1
blue.confNotice what was fast and what was not. The switch itself (symlink, nginx -t, reload) takes about a second. Detection takes as long as your evaluation window: here 50 requests, in production the 5-minute window described above. A metric-driven rollback cannot be faster than the time it needs to see enough errors. Stop the lab with nginx -p "$PWD/" -c "$PWD/nginx.conf" -e "$PWD/logs/error.log" -s quit and kill %1 %2.
After a successful deployment where Green stays healthy, keep Blue running for a safety window (for example 24 hours) before you decommission it or reuse it as the target for the next release.
04. Check your understanding
05. Apply it
Add a health gate before the switch and a latency rule to the watch, in the same bluegreen-lab/ directory. This takes about 30 minutes.
- In
cutover.sh, before the symlink is swapped, call the target stack's/healthzdirectly (port 8081 for blue, 8082 for green) and stop withtarget not healthy: <stack>and exit 1 if it does not answer 200. Test it: with Blue active, stop Green's backend (kill %2) and run./cutover.sh green.readlink active.confmust still showblue.conf. Start Green again afterwards. - Add a
SLOW_MSsetting tobackend.pythat makes every ordinary request wait that many milliseconds, and restart Green withSLOW_MS=1500and noFAIL_EVERY. Changewatch.shso that it also counts a request as bad whencurl -w '%{time_total}'reports more than 1 second. Before you run./watch.sh 20 1after a cutover, predict how many of the 20 requests will count as bad and how long the window will take. - Write down, for the error run in step 6 and the slow run here, how long it took from the cutover until the rollback, and what you would change to detect a slow release sooner.
Produce: your versions of cutover.sh, watch.sh and backend.py, the output of both tests, and the timing notes.
06. Review prompt
Describe how a Blue-Green deployment architecture avoids downtime and makes rollbacks fast behind a reverse proxy, and what still limits both. Contrast the resource cost of Blue-Green with Rolling Updates, explain how nginx -s reload gracefully preserves in-flight connections during cutover, and detail why database schemas must remain compatible with both stacks simultaneously.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.