Zero-Downtime Nginx Deployment on Ubuntu & AWS: Upstream Switching and Blue-Green Automation
Hello, this is Lovefield.
Once you automate Docker builds and deployments to an Ubuntu server on AWS EC2, the next operational friction point shows up immediately: brief downtime during every release.
In a single-container setup, running docker compose up -d --force-recreate stops the active container before the new one finishes booting. For anywhere from a few seconds to half a minute, Nginx serves 502 Bad Gateway errors to active users. While you could restrict releases to off-peak hours, that quickly breaks down the moment you need to ship an urgent hotfix during business hours.
At the same time, introducing Kubernetes or multi-target AWS ALB orchestration for a single-node service often adds unnecessary cost and operational overhead. In this guide, we will build a clean, automated Blue-Green zero-downtime deployment architecture on a single Ubuntu/AWS server using Nginx upstream switching and Docker.
How Nginx reload Avoids Dropping Connections
The foundation of zero-downtime routing in Nginx is Graceful Reload (nginx -s reload or systemctl reload nginx):
The Nginx master process validates the updated configuration syntax and loads it into memory.
It spawns new worker processes using the updated upstream target to accept incoming connections immediately.
It sends a graceful shutdown signal (SIGQUIT) to the old worker processes. Old workers stop accepting new connections, finish serving all in-flight HTTP requests completely, and then exit cleanly.
By booting a new Docker container (Green) on a separate local port, verifying its health endpoint, and reloading Nginx to point at it, users transition seamlessly without seeing a single dropped request.
Defining Blue and Green Services in Docker Compose
Split your application into two services—Blue (3001) and Green (3002)—bound strictly to 127.0.0.1 so external traffic can only pass through Nginx.
YAML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# docker-compose.yml
x-app-common: &app-common
image: dico-web:latest
restart: unless-stopped
env_file:
- .env.production
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
services:
app-blue:
<<: *app-common
container_name: dico-web-blue
ports:
- "127.0.0.1:3001:3000"
app-green:
<<: *app-common
container_name: dico-web-green
ports:
- "127.0.0.1:3002:3000"Using a YAML anchor (&app-common) avoids duplicating environment files and log rotation rules across both slots.
Isolating the Active Nginx Upstream
Avoid letting deployment scripts rewrite your main virtual host file (/etc/nginx/conf.d/dico.conf), which risks corrupting SSL or header rules. Instead, isolate the active upstream address into a tiny dedicated include file (active-upstream.inc).
Create the Active Upstream File (/etc/nginx/conf.d/active-upstream.inc)
Nginx
1
2
# Initial default: Blue (3001) active
server 127.0.0.1:3001;Virtual Host Configuration (/etc/nginx/conf.d/dico.conf)
Nginx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
upstream dico_backend {
include /etc/nginx/conf.d/active-upstream.inc;
keepalive 32;
}
server {
listen 80;
server_name dico.me;
location / {
proxy_pass http://dico_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
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;
# Guard against slow upstream responses
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
}
}Combining keepalive 32; inside the upstream block with proxyhttpversion 1.1; and proxysetheader Connection ""; allows Nginx to reuse persistent TCP connections to your local Docker container, reducing proxy latency.
Automating Blue-Green Switching (deploy.sh)
Here is a self-contained shell script that handles the entire release lifecycle safely:
Detects which slot (Blue or Green) is currently live and selects the idle target.
Builds (or pulls) the latest image and starts the target container.
Polls the /api/health endpoint until it returns 200 OK—aborting cleanly if the new build fails without touching live traffic.
Updates active-upstream.inc, validates syntax via nginx -t, and runs systemctl reload nginx.
Waits briefly for connection draining before stopping the old container.
Shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env bash
set -euo pipefail
UPSTREAM_FILE="/etc/nginx/conf.d/active-upstream.inc"
HEALTH_PATH="/api/health"
MAX_RETRIES=15
RETRY_INTERVAL=2
# 1. Detect active slot and choose target slot
if grep -q "127.0.0.1:3001" "$UPSTREAM_FILE"; then
CURRENT_COLOR="blue"
TARGET_COLOR="green"
TARGET_PORT=3002
else
CURRENT_COLOR="green"
TARGET_COLOR="blue"
TARGET_PORT=3001
fi
echo ">>> Active: ${CURRENT_COLOR} | Deploying to: ${TARGET_COLOR} (port ${TARGET_PORT})"
# 2. Build (or pull) image and start idle container
DOCKER_BUILDKIT=1 docker build -t dico-web:latest .
docker compose up -d --no-deps --force-recreate "app-${TARGET_COLOR}"
# 3. Healthcheck loop
echo ">>> Running healthcheck against ${TARGET_COLOR}..."
HEALTHY=false
for i in $(seq 1 "$MAX_RETRIES"); do
if curl -fsS "http://127.0.0.1:${TARGET_PORT}${HEALTH_PATH}" > /dev/null 2>&1; then
HEALTHY=true
echo ">>> Healthcheck passed (${i}/${MAX_RETRIES})"
break
fi
echo " Waiting for container... (${i}/${MAX_RETRIES})"
sleep "$RETRY_INTERVAL"
done
if [ "$HEALTHY" != true ]; then
echo ">>> [ERROR] ${TARGET_COLOR} failed healthcheck. Keeping ${CURRENT_COLOR} live and aborting."
docker compose stop "app-${TARGET_COLOR}"
exit 1
fi
# 4. Switch Nginx upstream and reload gracefully
echo "server 127.0.0.1:${TARGET_PORT};" | sudo tee "$UPSTREAM_FILE" > /dev/null
sudo nginx -t
sudo systemctl reload nginx
echo ">>> Traffic switched to ${TARGET_COLOR} (:${TARGET_PORT})."
# 5. Allow brief draining before stopping previous container
sleep 5
docker compose stop "app-${CURRENT_COLOR}"
echo ">>> Stopped ${CURRENT_COLOR}. Zero-downtime deployment complete!"> Tip: By leaving the previous container stopped (docker compose stop) instead of deleting it immediately, you can execute a 10-second emergency rollback simply by starting the previous slot and reverting the port in active-upstream.inc.
Three Production Gotchas on AWS EC2
While single-server Blue-Green deployment is lightweight, keep these three operational details in mind:
Temporary 2× Memory Overhead & Swap Space
During the overlap window, both Blue and Green containers run concurrently. On smaller EC2 instances like t3.small (2GB RAM), this can trigger the Linux OOM Killer. Cap per-container memory limits in Compose and configure at least 2GB of Swap space on Ubuntu as a safety cushion.
Backward-Compatible Database Migrations
For several seconds during cutover, both old and new versions query the same database. Avoid destructive migrations (like immediately renaming or dropping columns) in a single release—use the Expand and Contract pattern instead.
Scoped sudo Permissions for CI/CD
When triggering deploy.sh from GitHub Actions via SSH, avoid granting blanket passwordless sudo. Restrict /etc/sudoers.d/deploy strictly to nginx -t, systemctl reload nginx, and writing to /etc/nginx/conf.d/active-upstream.inc.
Summary
Zero-downtime releases do not require a full container orchestration platform. With an isolated Nginx upstream include, Graceful Reload, and a ~50-line health-checked Blue-Green script, you can ship updates confidently at any hour on a single AWS EC2 instance.
If deployments have felt stressful on your production server, setting up this Blue-Green switch is one of the simplest and highest-value upgrades you can make to your workflow.
This article was generated by AI.

Lovefield
Web Front-End developer
하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.

Unifying Frontend Linting and Formatting with Biome: Replacing ESLint + Prettier in a Bun Setup
Learn how to replace complex ESLint and Prettier setups with Biome v2 in a Bun environment. This practical guide covers biome.json configuration, VS Code integration, fast pre-commit hooks with Lefthook, and key considerations for Vue/Nuxt projects.
Java Script