Nginx Under Observation: Metrics, Alerts, and a 30-Second Rollback Drill
This is the 14th article in the "Nginx from Beginner to Master" series (15 articles total + 4 hands-on projects). Goal: turn "it runs" into "monitored, auditable, canary-able, and rollback-able" — deliver metrics + alerts + dashboards, and use a pipeline (render →
nginx -t→ reload → probe → rollback on failure) to prove: bad config never reaches production, and if it does, it rolls back to the previous version within 30 seconds.Prerequisites: Article 9 (log troubleshooting)'s
log_formatfields and$request_id, Article 7 (advanced load balancing)'szone/resolve, Article 8 (cache)'s$upstream_cache_status; experiments reuselab/00-env(as needed). All numbers and output in this article were actually measured with nginx 1.30.6 (stable), with 5 self-test questions and further reading at the end.
1. Get It Running (5-Minute Experiment)
Three containers show you "where metrics come from and where they go": start the lab gateway (8080), then Prometheus and Grafana.
cd nginx/lab/00-env && docker compose up -d # gateway 8080 + app1/2/3
docker network create ch14net 2>/dev/null || true # disposable containers, docker rm -f after
docker run -d --name ch14-prom --network ch14net -p 127.0.0.1:19090:9090 \
-v $PWD/prom:/etc/prometheus:ro prom/prometheus:latest --config.file=/etc/prometheus/prometheus.yml
docker run -d --name ch14-grafana --network ch14net -p 127.0.0.1:13000:3000 grafana/grafana:latest
curl -s localhost:8080/nginx_status # minimal metrics: stub_status
curl -s localhost:8080/metrics/vts-prom | head -3 # dimensional metrics: vts (enabled in section 4)
curl -s localhost:19090/api/v1/query --data-urlencode 'query=sum(rate(nginx_vts_server_requests_total{host="*"}[1m]))'
| Command | Expected output (measured) | Explanation |
|---|---|---|
/nginx_status |
Active connections: 2 / 326 326 355 / Reading: 0 Writing: 1 Waiting: 1 |
Only 3 connection counts + 3 cumulative counters, no dimensions |
/metrics/vts-prom |
First line # HELP nginx_vts_info, followed by nginx_vts_info{hostname="…",module_version="v0.2.7",version="1.30.6"} 1 |
Without buckets: 125 lines; with buckets: measured 373 lines / 329 series, containing extra dimensions for server/upstream/cache |
| PromQL QPS query | {"result":[{"value":[…,"1.766"]}]} |
The scrape endpoint needs traffic first, otherwise rate() is 0 |
Conclusion in five minutes: stub_status only answers "is the gateway alive?", not "which upstream is slow, or which status codes are rising". To answer that, you need dimensions (vts / lua) or compute from logs (see 2.1).
Experiment environment notes: Every number in this article was actually run. To avoid touching any files under
lab/00-env, the metrics experiments ran in disposable containers in/tmp/ch14: the gateway usednginx:stable-alpine(measurednginx/1.30.6) with the vts module appended (compiled, v0.2.7), another container ranopenresty/openresty:alpine(1.31.8.1) for the lua metric version, the backend directly mountedlab/00-env/app/app.py, host ports18080/18081/18082(Prometheus19090, Grafana13000). When you followcd nginx/lab/00-env && docker compose up -donlocalhost:8080, the instructions, fields, and judgment methods are identical, only the upstream IPs become the container IPs ofapp1/app2/app3.
2. Core Concepts
2.1 Four Ways to Source Metrics: Calculate the Cost First
| Approach | What you get | Extra components | Cost / pitfalls | Best for |
|---|---|---|---|---|
stub_status |
Connection counts, three cumulative values (accepts/handled/requests) | None (built-in --with-http_stub_status_module) |
No dimensions, no status-code distribution, must be allowed to internal networks |
Liveness probes, minimal monitoring |
nginx-module-vts |
Per-host / upstream / backend / cache dimensions, including status codes and latency histograms | Requires self-compilation (--add-module, measured v0.2.7 + nginx 1.30.6) |
Uses shared memory, histogram buckets must be explicitly enabled (see section 7) | Main recommendation: one endpoint covers the whole site |
| OpenResty + lua prometheus | Arbitrary custom metrics (can carry business labels) | Needs ngx_lua (openresty or libnginx-mod-http-lua) |
Runs Lua on every request, log_by_lua gets heavier as it grows |
When you need business dimensions and label control |
| Log-to-metrics (Vector/Fluent Bit/Loki) | Any field (including $request_id, $upstream_cache_status) |
Collection/parsing components | Second-level latency, requires maintaining parser rules | Easiest when you already have a unified log platform |
The four can coexist: stub_status for load balancer health checks, vts for Prometheus, logs for troubleshooting — don't use one endpoint for three jobs.
2.2 Key Metrics Map on the Prometheus Side (vts naming, measured output)
| Metric | Type | Meaning | Which dashboard |
|---|---|---|---|
nginx_vts_server_requests_total{host,code} |
counter | Request count by host and status code; host="*" is the site-wide total |
QPS, error rate |
nginx_vts_upstream_requests_total{upstream,backend,code} |
counter | Requests each backend received and its returned status codes | Traffic splitting, canary share |
nginx_vts_upstream_response_duration_seconds_bucket{le} |
histogram | Pure upstream response latency histogram (needs buckets enabled) | Upstream latency P99 |
nginx_vts_main_connections{status} |
gauge | active/reading/writing/waiting/accepted/handled/requests |
Connection counts |
nginx_vts_server_cache_total{host,status} |
counter | Cache hit/miss/expired/bypass/stale/updating/revalidated |
Cache hit rate |
nginx_vts_main_shm_usage_bytes{shared} |
gauge | Zone used_size/used_node/free_size; when full, silently drops dimensions |
Capacity warning (section 7) |
2.3 Four Must-Have Dashboards (PromQL ready to paste)
| Dashboard | PromQL | Measured result |
|---|---|---|
| ① QPS & error rate | sum(rate(nginx_vts_server_requests_total{host="*"}[1m]))sum(rate(...{host="*",code="5xx"}[1m])) / sum(rate(...{host="*"}[1m])) |
3.374 req/s; mixing in /dead/ raised error rate to 0.4236 (42.36%) |
| ② Upstream latency P99 | histogram_quantile(0.99, sum by (le) (rate(nginx_vts_upstream_response_duration_seconds_bucket[5m]))) |
Light load 0.0485s; with 12 concurrent /slow/ (backend sleeps 2s) 1.27s |
| ③ Connection count | nginx_vts_main_connections{status="active"} |
1; pair with waiting to watch long-connection buildup |
| ④ Cache hit rate | sum(rate(nginx_vts_server_cache_total{host="*",status="hit"}[5m])) / ignoring(status) group_left sum(rate(nginx_vts_server_cache_total{host="*"}[5m])) |
Single-URL high-frequency access 0.975; with random parameters drops to 0.048 |
2.4 Logging: Structured + $request_id + traceparent — Three Divisions of Labor
| Approach | Scope | What it solves | Implementation |
|---|---|---|---|
log_format with escape=json (requires ≥1.11.8) |
Single-machine logs | Collectors don't need to write regex | Short field names, numbers without quotes |
$request_id (≥1.11.0, 32-char hex) |
Within the gateway | Links access/error/upstream logs together | Log field rid; write back X-Request-Id in response header |
traceparent (W3C Trace Context) |
Across services | Links gateway, application, and downstream spans into a tree | map to extract/generate + proxy_set_header to pass through |
Measured: when the client doesn't send traceparent, the gateway auto-generates 00-53439abbd74023b3c05e26c6763e72c2-53439abbd74023b3-01 (trace-id is $request_id, span-id takes the first 16 chars); when the client sends 00-4bf92f35…4736-00f067aa0ba902b7-01, it passes through unchanged. The log's trace field is 53439abb… and 4bf92f35… respectively — logs can be grouped by trace, metrics cannot, that's the division of labor.
2.5 Alerts: From "5xx Beyond Threshold" to "Error Budget Burn"
| Alert | Expression key points | Why written this way |
|---|---|---|
| 5xx ratio | sum(rate(...{host="*",code="5xx"}[1m])) / sum(rate(...{host="*"}[1m])) > 0.05 |
Must include host="*", otherwise data is double-counted across _, *, and each host (measured 116 vs 58, exactly 2x) |
| Upstream all down | sum(increase(nginx_vts_upstream_requests_total{code="5xx"}[2m])) > 0 AND logs show no live upstreams |
5xx might be application logic; no live upstreams is always a topology issue |
| Certificate expiry | (probe_ssl_earliest_cert_expiry - time()) / 86400 < 7 |
blackbox_exporter probe metric, more reliable than "remember to renew" |
| 499 spike | sum(rate(nginx_vts_server_requests_total{code="499"}[5m])) > threshold |
Client giving up first = slow query/timeout, appears earlier than 5xx |
| Cache hit drop | Hit rate compared with offset 1h, drop > 20% |
Hit rate falling = key changed or upstream sent no-store |
| Error budget burn rate | 5xx ratio / SLO allowed ratio > 14.4 (1h window) |
Upgrade a ratio alert into a budget alert, fewer false positives at low traffic |
2.6 Configuration as Code: A Pipeline with Five Failure Exits
values/dev|staging|prod.json
│ ① render (Jinja2 StrictUndefined) → candidates/<env>.conf
▼ ② nginx -t ── fail ──> no reload, zero production impact (measured 0.2s exit)
▼ ③ backup active → replace → nginx -s reload
▼ ④ probe (/healthz consecutive 5x 200) ── fail ──> ⑤ restore backup + reload + re-probe (measured 9.5s recovery)
2.7 Canary Release Checkpoints and Rollback Trigger Conditions
| Phase | Action | Checkpoint (use real metrics) | Rollback trigger |
|---|---|---|---|
| Join | New member weight=1, others weight=10 |
New member share ≈ 1/31 ≈ 3.2% (measured 10/300 = 3.3%) | Share > 10% (weights not taking effect) or = 0 (resolve didn't resolve) |
| Observe | Only watch new member's 5xx and latency | upstream_requests_total{backend="new-IP",code="5xx"}, upstream_response_seconds |
New member 5xx ratio > 2x old members, or P99 up 50% |
| Scale up | weight 5 → 10 → take old version down |
Error rate and P99 don't degrade within 5 min after scale-up | Any step exceeds threshold → change back to previous weight and reload |
| Reclaim | Remove old member | Old member count returns to zero | — |
2.8 Retention, Masking, and Sampling (Cost and Compliance Perspective)
| Item | Suggestion | Cost |
|---|---|---|
| Retention | Hot 7 days full, warm 90 days compressed, cold 1 year summary | Using URI histograms instead of full text saves about 90% |
| Masking + sampling | map to rewrite token, email params to *** before writing; don't log Authorization; sample 2xx at 10%, keep all 4xx/5xx, never sample metrics |
Rewriting changes aggregation semantics; after sampling, count must be multiplied back by the sampling rate |
| Cardinality | Labels only host/status/upstream, never use $request_uri as a label |
High cardinality can blow up Prometheus memory |
3. Directive Details
| Directive | Default | Context | Explanation and pitfalls |
|---|---|---|---|
stub_status |
— | server/location |
Parameterless syntax ≥1.7.5 (old syntax stub_status on;; missing semicolon gives invalid number of arguments). Must pair with allow |
allow / deny |
Allow all | http/server/location |
Match in order, first match wins; deny all must be last |
access_log |
logs/access.log combined |
http/server/location |
Inside location it overrides, not appends; metric endpoints need access_log off |
log_format … escape=json |
None | http |
≥1.11.8; only escapes ", \, and control chars; don't quote numeric fields |
$request_id |
16-byte random | Readable in all phases | ≥1.11.0, 32-char hex, naturally fits trace-id format |
map |
None | http |
For empty string values write a "" branch, otherwise it forwards an empty header; result can't reference itself |
vhost_traffic_status_zone |
None (not collected if off) | http |
Third-party module; each node uses fixed 3547 bytes, 2m zone measured max 507 nodes (section 7) |
vhost_traffic_status_histogram_buckets |
None | http |
Without it only mean exists, histogram_quantile() returns empty; with it, 72 more _bucket series (measured) |
vhost_traffic_status_display |
on |
http/server/location |
Content controlled by accompanying …_display_format (default json for humans, must explicitly write prometheus for scraping, otherwise parsing fails); production must allow |
lua_shared_dict |
None | http |
lua metric storage; 10m is enough for dozens of label combos, scale up with more labels |
init_worker_by_lua_block |
None | http |
Metrics must be registered here; writing into init_by_lua_block gives counter not initialized (hit this in practice) |
log_by_lua_block |
None | http/server/location |
Runs per request, only do inc/set/observe, don't send network requests here |
proxy_set_header |
Inherits from parent | http/server/location |
Setting any one stops inheritance of the whole parent group; when passing through, don't forget to keep Host |
4. Complete Configuration Examples
Relative to lab/00-env, only 4 types of changes: JSON logging, trace map + pass-through, cache and hit-rate fields, metric endpoints. The main context (user / worker_processes 1 / error_log / pid / events) is identical to lab, only http{} and below are listed.
First part /etc/nginx/lab/nginx.conf:
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Change ①: keep human-readable log from Article 9, add a machine-readable JSON log
log_format main '$remote_addr - "$request" $status rt=$request_time '
'urt=$upstream_response_time up=$upstream_addr';
log_format json_log escape=json
'{"ts":"$time_iso8601","rid":"$request_id","host":"$host","method":"$request_method",'
'"uri":"$request_uri","status":$status,"rt":$request_time,"urt":"$upstream_response_time",'
'"up":"$upstream_addr","ustatus":"$upstream_status","cache":"$upstream_cache_status",'
'"trace":"$trace_id","bytes":$body_bytes_sent,"xff":"$http_x_forwarded_for"}';
access_log /var/log/nginx/lab_access.log main;
access_log /var/log/nginx/lab_access_json.log json_log;
sendfile on;
keepalive_timeout 65;
gzip on;
gzip_types text/css application/javascript application/json text/plain;
resolver 127.0.0.11 valid=5s ipv6=off;
# Change ②: tracing trio — $request_id as trace-id, first 16 chars as span-id
map $request_id $trace_span_id { "~*^(?<s>[0-9a-f]{16})" $s; }
map $http_traceparent $traceparent_up {
default $http_traceparent; # upstream already has one → pass through
"" "00-$request_id-$trace_span_id-01"; # missing → generate one
}
map $http_traceparent $trace_id {
"~*^[0-9a-f]{2}-(?<t>[0-9a-f]{32})-" $t;
default $request_id; # align with log rid, never empty
}
# Change ③: cache only for hit-rate calculation (key review in Article 8)
proxy_cache_path /var/cache/nginx/lab levels=1:2 keys_zone=lab_cache:4m max_size=64m inactive=1m;
upstream app_pool {
zone app_pool 64k;
server app1:8080 resolve max_fails=3 fail_timeout=10s;
server app2:8080 resolve max_fails=3 fail_timeout=10s;
server app3:8080 resolve max_fails=3 fail_timeout=10s;
}
include /etc/nginx/lab/conf.d/*.conf;
}
Second part /etc/nginx/lab/conf.d/default.conf (only changes listed; /static/, /slow/, / are same as lab):
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location = /healthz { access_log off; return 200 "gateway ok\n"; }
# Change ④: status page logs off + internal only (lab relaxes 172.16/12 for container network)
location /nginx_status {
access_log off;
stub_status;
allow 127.0.0.1;
allow 10.0.0.0/8;
allow 172.16.0.0/12;
deny all;
}
location /api/ {
proxy_pass http://app_pool/;
proxy_connect_timeout 2s;
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_set_header traceparent $traceparent_up; # Change ② landing
proxy_cache lab_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 10s;
proxy_ignore_headers Cache-Control Expires; # app sends no-store, don't ignore or never hit
add_header X-Cache-Status $upstream_cache_status always;
}
}
Third part is the metric endpoint, choose one of two (paste into the above server block; the vts version also needs the two zone lines added in the http{} block above):
# Option A: vts (requires compiling third-party module, measured v0.2.7 + nginx 1.30.6) — add in http{}:
vhost_traffic_status_zone shared:vts_zone:2m;
vhost_traffic_status_histogram_buckets 0.005 0.01 0.05 0.1 0.5 1 3 5;
location = /metrics/vts-prom {
access_log off;
vhost_traffic_status_display;
vhost_traffic_status_display_format prometheus;
allow 127.0.0.1; allow 10.0.0.0/8; allow 172.16.0.0/12; deny all;
}
# Option B: OpenResty + lua prometheus (measured openresty 1.31.8.1); add in http{}:
# Registration must be in init_worker, writing init_by gives counter not initialized
lua_package_path "/etc/nginx/lab/lua/?.lua;;";
lua_shared_dict prometheus_metrics 10m;
init_worker_by_lua_block {
prometheus = require("prometheus").init("prometheus_metrics")
metric_requests = prometheus:counter("nginx_http_requests_total", "请求数", {"host","status"})
metric_up_req = prometheus:counter("nginx_upstream_requests_total", "上游请求", {"upstream","code"})
metric_up_rt = prometheus:gauge("nginx_upstream_response_seconds", "上游耗时", {"upstream"})
metric_latency = prometheus:histogram("nginx_http_request_duration_seconds", "耗时", {"host"},
{0.05, 0.1, 0.3, 0.5, 1, 2, 5})
metric_cache = prometheus:counter("nginx_cache_status_total", "缓存状态", {"status"})
}
log_by_lua_block {
metric_requests:inc(1, {ngx.var.host, ngx.var.status})
metric_up_req:inc(1, {ngx.var.upstream_addr or "none", ngx.var.upstream_status or "none"})
metric_up_rt:set(tonumber(ngx.var.upstream_response_time) or 0, {ngx.var.upstream_addr or "none"})
metric_latency:observe(tonumber(ngx.var.request_time) or 0, {ngx.var.host})
metric_cache:inc(1, {ngx.var.upstream_cache_status or "-"})
}
location = /metrics {
access_log off;
content_by_lua_block { prometheus:collect() }
allow 127.0.0.1; allow 10.0.0.0/8; allow 172.16.0.0/12; deny all;
}
Option B measured output (/metrics, without # comment lines): nginx_http_requests_total{host="localhost",status="200"} 3, nginx_upstream_response_seconds{upstream="172.28.0.3:8080"} 0.004, nginx_cache_status_total{status="MISS"} 3, nginx_metric_errors_total 0, nginx_http_request_duration_seconds_bucket{host="localhost",le="0.05"} 3.
Alert rules rules.yml (promtool check rules measured SUCCESS: 2 rules found):
groups:
- name: nginx-lab
rules:
- alert: NginxHigh5xxRatio
expr: |
sum(rate(nginx_vts_server_requests_total{host="*",code="5xx"}[1m]))
/
sum(rate(nginx_vts_server_requests_total{host="*"}[1m])) > 0.05
for: 2m # drill uses 0m; production don't go below 2m, otherwise flapping
labels: {severity: critical, service: lab-gateway}
annotations: {summary: '5xx ratio {{ $value | humanizePercentage }} over 5%'}
- alert: NginxTLSCertExpiringSoon
expr: (probe_ssl_earliest_cert_expiry - time()) / 86400 < 7
for: 0m
labels: {severity: warning, service: lab-gateway}
annotations: {summary: '{{ $labels.instance }} cert expires in {{ $value | printf "%.2f" }} days'}
Configuration as code: Jinja2 template + rendering script:
# templates/nginx.conf.j2 (excerpt: variables all from values/<env>.json; main context same as lab)
worker_processes {{ workers }};
error_log /var/log/nginx/lab_error.log {{ error_level }};
http {
resolver 127.0.0.11 valid={{ resolver_ttl }} ipv6=off;
proxy_cache_path /var/cache/nginx/lab levels=1:2 keys_zone=lab_cache:{{ cache_zone }} max_size={{ cache_max }} inactive=1m;
upstream app_pool {
zone app_pool 64k;
{% for m in members %}
server {{ m }}:8080 resolve max_fails=3 fail_timeout=10s;
{% endfor %}
}
}
"""render.py: render templates/nginx.conf.j2 + values/<env>.json -> out/<env>.conf"""
import json, pathlib, sys
from jinja2 import Environment, FileSystemLoader, StrictUndefined
base = pathlib.Path(__file__).parent
env = Environment(loader=FileSystemLoader(str(base / "templates")), # template dir
undefined=StrictUndefined, # missing variable raises error, not rendered empty
trim_blocks=True, lstrip_blocks=True)
tpl = env.get_template("nginx.conf.j2")
for name in sys.argv[1:] or ["dev", "staging", "prod"]:
v = json.loads((base / "values" / f"{name}.json").read_text())
(base / "out" / f"{name}.conf").write_text(tpl.render(**v))
Deployment script: nginx -t catches config errors, probe catches functional errors:
#!/bin/sh
# Usage: nginx-deploy.sh <candidate.conf> exit code 0=success 1=-t caught 2=rolled back 3=rollback failed too
set -u
ACTIVE=/etc/nginx/lab/active/nginx.conf
BACKUP=/etc/nginx/lab/backup/nginx.conf.$(date +%s)
PROBE=http://127.0.0.1/healthz
probe() { n=0; while [ $n -lt 5 ]; do wget -q -T 2 -O /dev/null "$PROBE" || return 1; n=$((n+1)); done; }
wait_up() { n=0; while [ $n -lt 5 ]; do wget -q -T 2 -O /dev/null "$PROBE" && return 0; n=$((n+1)); sleep 1; done; return 1; }
rollback() {
echo "[deploy] rollback: $1"; cp "$BACKUP" "$ACTIVE"; nginx -t -c "$ACTIVE" >/dev/null 2>&1 && nginx -s reload
sleep 2; wait_up && probe || { echo "[deploy] still down after rollback, manual intervention"; exit 3; }
echo "[deploy] back to previous version"; exit 2
}
cp "$ACTIVE" "$BACKUP" || exit 4
cp "$1" "$ACTIVE" || exit 4
nginx -t -c "$ACTIVE" || { cp "$BACKUP" "$ACTIVE"; echo "[deploy] -t failed, no reload, zero production impact"; exit 1; }
nginx -s reload || rollback "reload failed"; sleep 2 # old workers still hold ports during exit, probe can be false-positive
wait_up && probe || rollback "probe failed after reload"
echo "[deploy] publish success, backup $BACKUP"
5. Required Experiments
Experiment 1: Three Endpoints, Four Exits
curl -s localhost:8080/nginx_status # stub_status: 3 connections + 3 cumulative
curl -s localhost:8080/metrics/vts-prom | grep -c '^nginx' # vts: measured 125 lines (373 with buckets)
curl -s localhost:18081/metrics | grep -v '^#' # lua: custom metrics
docker compose stop app1; for i in $(seq 1 40); do curl -s -o /dev/null localhost:8080/api/; done # generate 5xx and traffic
Expected: /nginx_status gives only Active/Reading/Writing/Waiting; in vts-prom, nginx_vts_server_requests_total{host="_",code="5xx"} grows; in Prometheus, sum(...{code="2xx"}) is exactly 2x ...{host="*"} (measured 116 vs 58), because you added _, *, and each host together. This is the most important lesson: do not mix aggregation layers with detail layers.
Experiment 2: Two Alerts + Three "Out-of-Bounds" Scenes
openssl req -x509 -newkey rsa:2048 -days 5 -nodes -keyout lab.key -out lab.crt \
-subj "/CN=lab.example.com" # expires in 5 days, guaranteed trigger
curl -s localhost:19090/api/v1/alerts | python3 -m json.tool | grep -E 'alertname|state'
Measured both firing: NginxHigh5xxRatio value 0.4236, NginxTLSCertExpiringSoon value 4.9992 (days). Key points: cert alerts look at the probe's remaining days, not calendar reminders; for: 2m lets it survive one scrape failure.
Run three out-of-bounds scenes on the same pipeline (chaos drill):
| Drill | Command | Measured evidence |
|---|---|---|
| Cert expiring | 5-day self-signed cert | probe_ssl_earliest_cert_expiry - time() = 4.9995 days, alert firing |
| Upstream all down | docker stop app1 app2 app3 |
/api/ returns consecutive 502; error_log shows no live upstreams while connecting to upstream; vts has {upstream="app_pool",backend="app_pool",code="5xx"} growing |
| vts zone full | 2m zone + 700 hosts | From node 508 onward reports ngx_slab_alloc() failed: no memory in vhost_traffic_status_zone, usedNode stuck at 507 |
Experiment 3: Three Environments + -T Snapshot Diff
python3 render.py dev staging prod
for e in dev staging prod; do docker run --rm -v $PWD/out:/c:ro nginx:stable-alpine \
sh -c "nginx -t -c /c/$e.conf && nginx -T -c /c/$e.conf" > $e.dump; done # -T snapshot after -t
diff -u dev.dump prod.dump
Measured: all three environments test is successful; -T snapshots after template rendering: dev 13 lines / prod 15 lines, diff 12 lines changed, all expected differences (worker_processes 1 → auto, error_level info → warn, resolver valid=5s → 30s, keys_zone 4m → 64m, upstream 1 member → 3). Paste that diff into the PR, reviewers only look at those 12 lines. Missing variables cause rendering failure: UndefinedError: 'cache_zone' is undefined.
Experiment 4: Deployment Failure Auto-Rollback (All Three Endings)
| Candidate config | Measured output | Exit code | Time | Production impact |
|---|---|---|---|---|
Missing semicolon (stub_status no ;) |
[deploy] -t failed, no reload, zero production impact; stderr invalid number of arguments in "stub_status" |
1 | 0.2s | Zero |
| Normal config | [deploy] publish success, backup … |
0 | 2.2s | None |
listen 80 → listen 8081 (syntax valid, functionally broken) |
-t passes → reload → wait 2s then probe 5 times all failed → [deploy] rollback: probe failed after reload → back to previous version |
2 | 9.5s | about 7 seconds unavailable |
That's the proof of "rollback within 30 seconds", and it shows a CI gate that only runs nginx -t cannot catch functional errors — the third row of config passes -t cleanly.
Experiment 5: Canary Release + Rollback, Let Metrics Talk
# ① Join new version: app1/2/3 each weight=10, new member weight=1
# server app4:8080 resolve max_fails=3 fail_timeout=10s weight=1;
docker compose exec -T gateway nginx -t -c /etc/nginx/lab/nginx.conf
docker compose exec -T gateway nginx -s reload
for i in $(seq 1 300); do curl -s -o /dev/null "localhost:8080/api/json?cb=$i"; done # cb= bypass cache
# ② Check share: measured new member 10/300 = 3.3%, matching weight 1/31 = 3.2%
# ③ Rollback: delete that line and reload, new member has 0 hits out of 100 requests
Key: cb= must be added, otherwise /api/'s 10-second cache collapses 300 requests into 1 upstream request, the share is all noise. Rollback action = delete one line + nginx -t + reload, measured new weight takes effect within 1 second.
6. Acceptance Self-Test (5 Questions)
Q1. What questions are stub_status, vts, and lua prometheus each best suited for? Why can't you use only stub_status?
Answer key: stub_status only has connection counts + three cumulative counters, answers "is the gateway alive, are connections piling up"; no dimensions (can't group by host/upstream/status code), so it can't answer "which backend is slow, where do 5xx come from". vts has built-in host/upstream/backend/cache dimensions and a histogram, one endpoint covers the whole site, at the cost of compiling a third-party module and consuming shared memory. lua version can carry business labels (e.g., tenant), at the cost of running Lua per request.
Q2. Why must the 5xx ratio alert include host="*"?
Answer key: vts outputs both detail (each server_name) and two aggregate nodes _ (default server) and * (all). Without filtering, the same data is added two or three times; measured sum(...{code="2xx"}) = 116 while ...{host="*"} = 58, doubling the denominator makes alerts both dead and spurious. Same for cache, connection dashboards, you must lock to the same layer.
Q3. Does nginx -t passing mean the config is correct? Give a counterexample and remedy.
Answer key: No. -t only validates syntax and directive arguments. Changing listen 80 to listen 8081 is syntactically valid, -t passes, reload succeeds, but the service is unreachable — measured probe 5 times all Connection refused, script rolled back and restored. Remedy: the release pipeline must have "probe after reload (consecutive 5x 200) + auto-restore backup on failure + re-probe", and keep the previous version's conf and nginx -T snapshot for diff audit.
Q4. What's the division of labor between $request_id and traceparent? What if the client doesn't send traceparent?
Answer key: $request_id (≥1.11.0) is for in-gateway log correlation; traceparent is for cross-service call chains. When the client doesn't send one, use map to generate 00-$request_id-$trace_span_id-01 ($request_id is exactly 32-char hex, can directly be trace-id, first 16 chars as span-id), then pass with proxy_set_header traceparent $traceparent_up; also store trace field in logs (falls back to $request_id when no upstream trace), ensuring logs can always be grouped by trace.
Q5. How to estimate vts zone size? What happens when it fills up?
Answer key: Measured each node fixed 3547 bytes (usedSize = 3547 × usedNode holds exactly: 1 node 3547, 51 nodes 180897, 201 nodes 712947); node ≈ each server_name + each upstream group + each backend member + cache nodes. A 2m zone measured max 507 nodes, from node 508 onward prints ngx_slab_alloc() failed: no memory in vhost_traffic_status_zone, new dimensions silently drop metrics (Prometheus still scrapes old series, dashboard looks "normal"). Plan with node count × 4KB × 2 margin and alert on free_size.
7. Common Pitfalls
A host / new backend missing from dashboard, other graphs fine. Symptom: only new dimension has no data, error_log doesn't surface. Root cause: vts zone full and only writes to error.log (measured from node 508
no memory in vhost_traffic_status_zone). Fix: zone sizednode count × 4KB × 2; alert onfree_size; calculate capacity before adding dimensions.histogram_quantile()returns empty forever. Symptom: P99 dashboard empty but mean has a value. Root cause: novhost_traffic_status_histogram_buckets, only mean no buckets. Fix: explicitly enable buckets; measured adding buckets adds 72_bucketseries while zone usage unchanged (21331 bytes), cost is series cardinality, not nginx memory.Prometheus scrape inflates QPS, lowers hit rate. Symptom: metric endpoint's own scrape counted in request numbers. Root cause: metric endpoint didn't turn off logging, scrape requests also go into
access_log(measured log shows"ua":"Prometheus/3.15.1"). Fix: alwaysaccess_log offon metric/healthcheck locations.Lua metrics all zero, error.log reports
counter not initialized. Symptom:/metricsscrapes, series all zero. Root cause: metric registration ininit_by_lua_block(original text:Have you called Prometheus:init() from the init_worker_by_lua_block nginx phase?). Fix: move toinit_worker_by_lua_block.openresty won't start:
getpwnam("nginx") failed,mkdir /var/cache/nginxfails. Symptom: exits right after starting with a changed image. Root cause: OpenResty usesnobody, layout in/usr/local/openresty/, and no/var/cache/nginx. Fix: three places to change —user nobody;,mime.typespath, cache and log paths.Deployment "success" but service dead (false positive); or rollback immediately after probe fails (false negative). Symptom: probe all 5 pass, but
:80truly down milliseconds later. Root cause:reloadis async —-s reloadonly sends signal, master swaps listeners then takes effect, but old workers still hold the old port until they exit (measured after changinglisten 80to 8081, probing immediately 5 times all pass because it hit the old worker). Fix: after reloadsleep 2for old workers to exit before probing; more stable: probe an endpoint that only exists in the new config (e.g.,/versionwith config fingerprint).Canary share doesn't match graph. Symptom: weight 1/31, but metrics show new member near 100% or 0. Root cause:
/api/has 10s cache, same URL hits, 300 requests only hit upstream once. Fix: add unique param to traffic (?cb=$i), or disable cache for canary path.Alerts firing all day, nobody looks. Symptom: any jitter triggers
firing, after two weeks no one reads it. Root cause: threshold too low (5xx 0.1% triggers) + window too short. Fix:for: 2m+ error budget burn rate (only wake people whenburn rate > 14.4).
8. Further Reading
| Doc page | Solves what |
|---|---|
| ngx_http_stub_status_module | stub_status parameterless syntax version boundary and each field's meaning |
| ngx_http_log_module | log_format's escape=json (≥1.11.8) and access_log override/inheritance rules |
| Built-in variables index | authoritative definitions for $request_id, $upstream_*, $time_iso8601, etc. |
| ngx_http_map_module | map's empty-string branch, regex capture naming; trace header extraction depends on it |
| ngx_http_proxy_module | proxy_set_header inheritance rules, $upstream_cache_status values |
| ngx_http_api_module | what Plus's native API looks like for "runtime metrics without reload" (for comparison) |
| nginx-module-vts | all vts directives, Prometheus output format, zone calculation |
Chapter dependencies: This article ties together Article 9's log fields, Article 7's zone/resolve, Article 8's cache status into an alertable metrics layer; it's also the measurement basis for whether Article 13's canary and traffic draining can be accepted; Article 15's failure case library directly references this article's metric semantics, the difference between -t and probing, and the "don't mix aggregation layers" criterion.
Series navigation: Article 1 process model → 2 install/upgrade → 3 config syntax → 4 static sites and location → 5 reverse proxy → 6 rewrite and server_name → 7 advanced load balancing → 8 cache → 9 log troubleshooting → 10 HTTPS and security → 11 Lua and OpenResty → 12 performance tuning → 13 high availability architecture and gateway → 14 (this article) observability and engineering → 15 failure case library
Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.
As for rollback verification, there's an easily missed point: reload is a smooth switch, and the in-flight requests still on the old workers will write results into the same sequence according to the old config. So "rollback effective" is best observed by version slices — carry a config_version label in the conf, or log the hash of each nginx -T snapshot. Otherwise the 30 seconds of data after rollback will mix the two versions, and the recovery of the success rate gets misread as a successful rollback. Additionally, keepalive long connections mean that even after the weight is zeroed, traffic still hits the old upstream. For the verification window it's better to check whether the number of requests to new members within 60/120 seconds actually drops to zero, rather than whether it's zero out of 100 requests. In production it's not convenient to add cb= to bypass the cache; a more stable approach is to group by upstream in the same query and look at the change in the absolute count of 5xx errors.
Excellent, excellent, excellent.