Nginx 日志、监控与排障:全字段日志、条件日志与证据链定位

0 阅读14分钟

这是《Nginx 从入门到精通》系列的第 9 篇(全系列 15 篇 + 4 个实战项目)。目标:不靠猜——用「日志字段 → 连接/抓包 → 进程」三层证据,在 10 分钟内把 499/502/504 定位到具体的一段,并说清是哪一端慢。

前置:第 5 篇(upstream、max_fails 摘流)、第 7 篇(zone/resolve 与被动健康检查);log_format/map 的书写规则见第 3 篇,map 的取值游戏见第 6 篇;实验复用 lab/00-env。 本文所有数字与输出均为 nginx 1.30.6(stable)实测,文末附自测 5 题与延伸阅读。


1. 先跑起来(5 分钟实验)

五条命令跑出一次正常请求、一次慢请求、一次客户端放弃,然后回头读日志:

cd nginx/lab/00-env && docker compose up -d
curl -s localhost:8080/api/json                                  # 正常请求
curl -s -o /dev/null -w 'code=%{http_code} t=%{time_total}\n' localhost:8080/slow/
curl -s -o /dev/null --max-time 0.2 localhost:8080/slow/         # 客户端 0.2s 就放弃
docker compose exec -T gateway tail -n 3 /var/log/nginx/lab_access.log
命令预期输出(实测)谁在说话
curl -s localhost:8080/api/json"app": "app3" / app1 / app2 轮询第 5 篇的轮询仍然生效
... /slow/(lab 原配置 proxy_read_timeout 5s,后端 sleep 2s)code=200 t=2.0046322 秒全花在上游
--max-time 0.2 ... /slow/curl exit=28(客户端主动放弃)客户端先走,网关记 499
对应日志两行"GET /slow/ HTTP/1.1" 200 21 rt=2.003 urt=2.003 up=172.30.0.4:8080
"GET /slow/ HTTP/1.1" 499 0 rt=0.201 urt=0.200 up=172.30.0.3:8080
见 2.1 的字段表

五分钟能得到的第一个结论:rt 与 urt 一起读。两条请求都慢到 rt≈urt,说明时间全在上游(应用侧);如果哪天 rt 远大于 urt,时间就在客户端侧或网关自身。第二个结论更重要:499 不会被记进 warn 级的 error_log——只开 error_log 的人永远看不到它。

实测环境说明:下面每一条日志行、每一个耗时都是真跑出来的。写这篇时本机 8080 被别的进程占用,我把 lab/00-env 复制到 /tmp/lab09、只改宿主端口(19090:80)和容器名前缀再跑同一套配置,所以实测行里出现 localhost:19090、上游 IP 是 172.30.0.x。你在自己机器上按 cd nginx/lab/00-env && docker compose up -d 用 localhost:8080 跑,字段顺序与判断方法完全一致,up= 后面会是 app_pool 成员的容器 IP。

2. 核心概念

2.1 一行日志 = 一次请求的结算单

lab 的 log_format main 已经埋好了主字段,本章在它之上再补几个。逐字段看,每个字段只回答一个问题:

字段含义实测取值回答什么问题
$request_time从读到请求首字节到响应发完的总耗时rt=2.003用户等多久
$upstream_response_time连上上游后到收完响应的时间,可多值urt=2.003 / urt=1.005, 1.002, 1.002上游自己慢不慢
$upstream_connect_time与上游建立 TCP 连接的耗时,可多值uct=0.007, 0.004, 0.002慢在网络/握手还是应用
$upstream_header_time从连上到收到上游响应头的耗时,可多值uht=-, -, -上游「首字节延迟」有多高
$upstream_addr真正连过的上游地址,多值up=172.30.0.4:8080, 172.30.0.3:8080这次打到谁(摘流是否生效)
$request_id32 位十六进制请求 ID(≥1.11.0)rid=a9f28ffb0e4209607886430acb18d295跨系统把同一个请求串起来
$connection / $connection_requests连接序号 / 这个连接上的第几个请求conn=144/1长连接复用到底有没有生效
$request_length / $bytes_sent / $upstream_bytes_received收到字节 / 发出字节 / 从上游收到字节in=86 out=314 urx=0, 0, 0是带宽问题还是逻辑问题
$status / $body_bytes_sent状态码 / 响应体字节200 296成没成、发了多少
$ssl_protocol客户端用的 TLS 版本(仅 https server 有值,本章 lab 无 TLS 故未实测)TLSv1.2/TLSv1.3握手降级没有(第 10 篇)

upstream_* 里的 - 是「本次没发生」:没有上游(静态文件、return)就是 -;上游超时未收到响应头,$upstream_header_time 就是 -(实测 uht=-, -, -)。别把 - 当 0 参与排序。

2.2 四个时间变量的时序:谁能解释谁

客户端 ──①请求──> nginx ──②connect──> 上游 ──③等响应头──> ④收响应体 ──⑤写给客户端──> 客户端
        |<───────────── $request_time ─────────────────────────────────────────>|
                   |<─ $upstream_connect_time ─>|<─ 到 $upstream_header_time ─>|<─ 到 $upstream_response_time ─>|
rturt实测样本(本章实验)结论下一步看什么
2.0032.003/slow/ 正常上游慢(应用)上游机器 CPU、应用日志、DB
3.8410.004POST /api/json 传 200KB(--limit-rate 50k)慢在客户端/传输侧,与上游无关客户端上行带宽、请求体大小(client_max_body_size)
3.0081.005, 1.002, 1.002/slow/ 被 proxy_read_timeout 1s 截断不是「一次慢 3 秒」,是三次各 1 秒的重试叠加proxy_next_upstream / 读超时
0.2010.200客户端 --max-time 0.2客户端先走,上游还在算客户端超时值、SLA

2.3 多值链:urt/up/uct/uht 是同一个意思的四个视角

只要有重试(proxy_next_upstream,默认 error timeout),这四个变量都会变成用 ", "(逗号 + 空格) 连接的列表,顺序就是重试顺序。实测一条 502:

"GET /api/json HTTP/1.1" 502 rt=0.501 uct=0.007, 0.004, 0.002 uht=-, -, - urt=0.149, 0.159, 0.194 up=198.18.41.234:8080, 198.18.41.233:8080, 198.18.41.232:8080

四个列表长度一致、按下标一一对应,rt=0.501 ≈ Σurt=0.502,说明这 0.5 秒全耗在三次上游尝试上。特例:上游全被摘掉时 $upstream_addr 写的是组名而不是地址,实测 up=app_pool、urt=0.000(没有 ", " 列表)。所以日志解析里出现「up= 后面不是 IP:端口」时,八成是全摘流,别当成脏数据。

2.4 状态码全谱:谁产生的、日志里长什么样

码谁产生实测的日志/错误日志特征30 秒内的下一步
400nginxerror_log 里 client sent invalid ... 系列(Host/URI 非法,具体措辞以实机为准)看请求头、large_client_header_buffers
403nginxaccess forbidden by rule(实测:宿主机访问 /nginx_status)看 allow/deny、目录权限
404nginx/静态访问 /nope-1 实测返回 200——lab 的 try_files ... /index.html 把 404 吃掉了先确认预期是 404 还是 SPA 回退
413nginxclient intended to send too large body: 2048 bytes调 client_max_body_size 或让客户端分片
499nginx 记录无 warn 级 error 行;body_bytes_sent=0、out=0、urx=0客户端超时/重试策略
500nginx 内部或应用rewrite or internal redirection cycle while processing "/loop"(实测 rewrite ^ /loop last; → 500)看应用日志;重写循环见第 6 篇
502nginxconnect() failed (111: Connection refused)、upstream prematurely closed connection while reading response header、no live upstreams while connecting to upstream上游进程/端口/摘流状态
503应用自身或 limit_req实测「全部上游摘光」返回的是 502 而不是 503别把 502 当 503 排查(见第 7 节)
504nginxupstream timed out (110: Operation timed out) while reading response header from upstreamproxy_read_timeout 与上游处理时长

2.5 三层证据链:日志 → 连接 → 抓包 → 进程

  1. 日志(秒级):grep ' 50[24] ' lab_access.log、看 up=/urt=,判断「哪一端、几次」;
  2. 连接:ss -s(总览)、ss -tanp state established(无 ss 用 netstat -tanp)、stub_status 的 Active/Reading/Writing/Waiting——Reading 高说明在收发请求头,Writing 高说明在写响应;
  3. 抓包:tcpdump -i any -nn port 8080 -A,看有没有「只发 SYN 没回 SYN-ACK」(不可达/丢包)、有没有 RST(谁先关的连接);
  4. 进程:strace -f -p <worker>(容器内需 --cap-add SYS_PTRACE)看 accept4/read/write 卡在哪,perf top 看 CPU 在干什么(第 12 篇)。

第 2 层最近的一个抓手是 stub_status,lab 的 /nginx_status 就开了它(实测输出,注意必须从容器内部访问,见第 7 节):

Active connections: 1
server accepts handled requests
 112 112 112
Reading: 0 Writing: 1 Waiting: 0

accepts/handled 相等说明没丢连接(不等就是 backlog 溢出或 worker_connections 不够);requests/accepts 是长连接复用倍数;Waiting 是空闲 keepalive 数,Active = Reading + Writing + Waiting。

2.6 日志落盘模型与成本

access_log 与 error_log 是两条完全不同的通道:前者是结构化的请求结算(每个请求一行,可格式化、可过滤、可转 JSON),后者是非结构化的事件流(级别 debug/info/notice/warn/error/crit/alert/emerg)。排障时两边的角色是「access 定位哪一次请求异常,error_log 解释为什么异常」。

IO 成本上有三件事必须知道:buffer=32k flush=5s 把每行 write 合并成批量写;open_log_file_cache 只省掉「每次写日志都 open 一次文件描述符」,不省 write;escape=json(≥1.11.8)让一行日志本身就是合法 JSON,能省掉 Loki/ELK 侧的正则解析。

注意官方镜像没有 --with-debug(nginx -V 里看不到该开关),把 error_log 调到 debug 实测只会多出 [info] 级消息(如 client 192.168.65.1 closed keepalive connection),拿不到 [debug] 行——要 debug 行得自己编译。

2.7 日志切割:reopen 才是关键那一步

直接 rm/mv 日志文件不会让 nginx 换文件——它握着的是文件描述符,不是路径。实测:mv lab_access.log lab_access.log.1 之后继续打请求,新日志仍然追加进 lab_access.log.1(文件涨到 13530 字节);只有发 USR1(nginx -s reopen)才会重新 open() 路径,此时新文件由 worker 用户创建(实测属主是 nginx root),旧 fd 关闭、磁盘空间才真正释放。

内容放在 /etc/logrotate.d/nginx-lab:

/var/log/nginx/lab_*.log {
    daily
    rotate 7
    missingok
    notifempty
    compress
    delaycompress
    create 0644 nginx nginx
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
    endscript
}

三处必须对齐:create 的用户要等于运行 worker 的用户(否则新文件写不进去,可用 su nginx nginx 兜底);sharedscripts 保证一次 reload 而不是每个文件一次;delaycompress 避免压缩正在写的文件。

容器里分两种:日志写 volume(像 lab 的 nginx-logs)就用宿主 cron/sidecar 跑 logrotate,但 kill -USR1 要在同一进程命名空间里(docker compose exec -T gateway nginx -s reopen 或 docker kill -s USR1 lab-gateway);日志写 stdout(官方镜像 /var/log/nginx/access.log → /dev/stdout 的软链)则交给 Docker 的 log-opts max-size/max-file,logrotate 完全插不上手。

3. 指令详解

指令默认值上下文说明与坑
log_format内置 combinedhttp名字自定义,名字被 access_log 引用;escape=json(≥1.11.8)出 JSON。不要把 $cookie_*、$http_authorization 写进格式,日志落地即泄露
access_loglogs/access.log combinedhttp/server/location/if in locationoff 关闭(lab 的 /healthz 就关了,实测 grep 计数 0);buffer=/flush= 降 IO;gzip= 压缩;if=(≥1.7.0)按条件落盘
error_loglogs/error.log errormain/http/server/location生产用 warn:既保留故障,又不被 info 刷爆;别忘了 499 在这里没有记录
open_log_file_cacheoffhttp/server/locationmax=1000 inactive=60s valid=1m min_uses=2,缓存 fd;只省 open,不省 write,高 QPS 还要配 buffer
map + access_log if=— / 无http / 位置同上map $status $loggable { ~^[45] 1; default 0; };if= 只接受一个变量,且只把 "0"/空串当「关闭」,写 ~^[45] 会连 4xx 一起捞进来(实测 403 混进了 5xx 文件)
stub_status—server/location只给 4 个数:Active connections、accepts/handled/requests、Reading/Writing/Waiting;必须配 allow/deny,但容器端口映射下 allow 127.0.0.1 挡不住宿主请求也放不过宿主请求(源 IP 是 Docker 网关)
log_subrequestoffhttp/server/locationauth_request 等子请求默认不写日志;打开后日志量翻倍,排障期才开
proxy_next_upstreamerror timeouthttp/server/location决定要不要重试 → 直接决定 urt/up 有几个值;重试会把延迟按段叠加(实测 3×1s=3s 才返回 504)
proxy_connect_timeout60shttp/server/locationlab 设 2s:上游不可达时秒级 502,而不是干等 60 秒(第 5 篇)
proxy_read_timeout60shttp/server/location「两次读之间」的超时,不是总时长;调小会更快吐 504,代价是把慢请求变成错误

4. 完整配置示例

相对 lab/00-env 改了这几处:主配置加 3 个 log_format(trace/jsonl/combined_ts)、3 条 access_log、1 个 map、open_log_file_cache;conf.d/default.conf 给 /api/ 加 X-Request-Id 透传,/slow/ 保留 5s。

主配置 /etc/nginx/lab/nginx.conf(只列 http{} 内与日志相关部分,其余同 lab/00-env):

worker_processes 1;
error_log  /var/log/nginx/lab_error.log warn;
pid        /var/run/nginx.pid;

events { worker_connections 1024; }

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # ① 运维主格式:够用、好 awk、和 lab 保持兼容
    log_format  main  '$remote_addr - $remote_user "$request" '
                      '$status $body_bytes_sent rt=$request_time '
                      'urt=$upstream_response_time up=$upstream_addr '
                      'xff="$http_x_forwarded_for"';

    # ② 排障格式:四段时间 + 请求 ID + 字节数,只在 4xx/5xx 时落盘
    log_format  trace '$remote_addr "$request" $status rt=$request_time '
                      'uct=$upstream_connect_time uht=$upstream_header_time '
                      'urt=$upstream_response_time up=$upstream_addr '
                      'rid=$request_id conn=$connection/$connection_requests '
                      'in=$request_length out=$bytes_sent urx=$upstream_bytes_received';

    # ③ 结构化格式:直接喂 Loki / ELK / jq,不用正则
    log_format  jsonl escape=json
                      '{"t":"$time_iso8601","rid":"$request_id","st":$status,'
                      '"rt":$request_time,"urt":"$upstream_response_time",'
                      '"up":"$upstream_addr","uri":"$uri","host":"$host",'
                      '"ua":"$http_user_agent","xff":"$http_x_forwarded_for"}';

    # ④ 给 goaccess 的一份 COMBINED:goaccess 认时间戳,必须有 $time_local
    log_format  combined_ts '$remote_addr - $remote_user [$time_local] '
                            '"$request" $status $body_bytes_sent '
                            '"$http_referer" "$http_user_agent"';

    # 条件落盘开关:1=记录,0=丢弃。只想留 5xx 就把正则改成 ~^5
    map $status $loggable { ~^[45] 1; default 0; }

    access_log  /var/log/nginx/lab_access.log   main;
    access_log  /var/log/nginx/lab_5xx.log      trace if=$loggable;
    access_log  /var/log/nginx/lab_json.log     jsonl;
    access_log  /var/log/nginx/lab_combined.log combined_ts;
    open_log_file_cache max=1000 inactive=60s valid=1m min_uses=2;

    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;

    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;
}

站点配置 /etc/nginx/lab/conf.d/default.conf(只贴改动的两个 location):

    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 X-Request-Id      $request_id;   # 新增:把 rid 传给上游
    }

    location /slow/ {
        proxy_pass http://app_pool;
        proxy_set_header Host $host;
        proxy_read_timeout 5s;      # 实验 1 会临时改成 1s 制造 504
    }
变更为什么验证点
trace 格式只在 if=$loggable 时写全量写 4 段时间,高 QPS 下 IO 翻倍wc -l lab_5xx.log 远小于 lab_access.log
jsonl 用 escape=json让 Loki/ELK 免正则jq -e . lab_json.log 能整行解析(无正则)
combined_tsgoaccess/Loki 的时间轴需要 $time_local无它则 goaccess 直接 fatal(实验 5)
open_log_file_cache省掉每条日志一次 open()语法校验通过即可,无需实测收益
X-Request-Id 透传上游日志里也能带同一个 ridcurl -s localhost:8080/api/json 回显的 headers 里出现 X-Request-Id

5. 必做实验

实验 1:制造 504,并证明「慢」是三次重试叠加的

把 /slow/ 的 proxy_read_timeout 改成 1s(后端 sleep 2s),校验、重载、打一次:

docker compose exec -T gateway nginx -t -c /etc/nginx/lab/nginx.conf
docker compose exec -T gateway nginx -s reload
curl -s -o /dev/null -w '%{http_code} %{time_total}\n' localhost:8080/slow/
docker compose exec -T gateway tail -n 1 /var/log/nginx/lab_access.log

预期(实测):

504 3.010133
"GET /slow/ HTTP/1.1" 504 167 rt=3.008 urt=1.005, 1.002, 1.002 up=172.30.0.4:8080, 172.30.0.3:8080, 172.30.0.2:8080

为什么是 3 秒不是 1 秒:默认 proxy_next_upstream error timeout 让它换下一个上游再试,三个上游各耗 1s 读超时,rt 是总账、urt 是分段账。这个实验的用处:看到 504 先看 urt 有几段——一段就是上游真慢,三段就是重试放大,该改的是重试策略(第 7 篇)。测完把 1s 改回 5s。

实验 2:制造 499,确认它不出现在 error_log 里

curl -s -o /dev/null --max-time 0.2 localhost:8080/slow/; echo "exit=$?"
docker compose exec -T gateway tail -n 1 /var/log/nginx/lab_access.log
docker compose exec -T gateway tail -n 3 /var/log/nginx/lab_error.log

预期(实测):

exit=28
"GET /slow/ HTTP/1.1" 499 0 rt=0.201 urt=0.200 up=172.30.0.3:8080

trace 行里 out=0 urx=0(一个字节都没发给客户端,上游也没回);error_log 里没有对应行。

为什么:499 是 nginx 自造的码,含义是「客户端在响应前断开」,对 nginx 来说不是错误事件;而 body_bytes_sent=0 是关键指纹——499 且字节为 0 说明响应还没开始发,499 且字节不为 0 说明是响应传到一半被掐断(大文件/慢网络)。区分 499 与 504 只看 urt:499 的 urt 通常小于超时值(上游还在正常算),504 的 urt 贴着你配的 proxy_read_timeout。

实验 3:502 + 三层证据链(日志 → 连接 → 抓包)

docker compose stop app1 app2 app3
for i in $(seq 12); do curl -s -o /dev/null -w '%{http_code} ' localhost:8080/api/json; done; echo
docker compose exec -T gateway tail -n 2 /var/log/nginx/lab_error.log
docker run --rm --net container:lab-gateway --cap-add NET_RAW alpine sh -c \
  'apk add -q tcpdump iproute2; ss -s; tcpdump -i any -nn -c 4 "tcp port 80"'
docker compose start app1 app2 app3   # 等 fail_timeout=10s 后自动恢复

预期(实测):for 循环那 12 次全是 502;error_log 与抓包输出如下。

no live upstreams while connecting to upstream, client: ..., request: "GET /api/json HTTP/1.1", upstream: "http://app_pool/json"
TCP: 347 (estab 0, closed 345, timewait 5)
IP 127.0.0.1.34444 > 127.0.0.1.80: Flags [S] ...

access 行是 502 157 rt=0.000 urt=0.000 up=app_pool;tcpdump 在 Flags [S] 之后紧跟 S.、.、HTTP: GET /api/json HTTP/1.1。

读法:up= 变成组名 + no live upstreams 就说明不是「某个后端挂了」而是「一个能用的都没有」(max_fails=3 把三个都摘了);抓包里 SYN 有回应说明网络通、问题在应用进程;等 10 秒(fail_timeout)自动恢复,说明摘流是临时的。

实验 4:map + if= 把 5xx 单独落盘(以及它骗了你一次)

用第 4 节的 map $status $loggable { ~^[45] 1; default 0; },跑一批混合请求后统计:

docker compose exec -T gateway awk '{print $5}' /var/log/nginx/lab_5xx.log | sort | uniq -c | sort -rn

实测:14 502 / 3 504 / 2 499 / 1 403——403 混进来了,因为 ~^[45] 同时匹配 4xx。把正则改成 ~^5 才是「只要 5xx」。

另外注意 access_log if= 的判定规则:只有值为 "0" 或空串算关闭,其它任何值(包括 "no")都算开启,所以 map 的 default 必须显式写 0。

实验 5:awk 分位数 + goaccess 出图

先算 rt 分位数(全部取值排序后按位置取,不依赖任何工具):

docker compose exec -T gateway cat /var/log/nginx/lab_access.log > /tmp/acc.log
awk -F'rt=' '{split($2,a," "); print a[1]}' /tmp/acc.log | sort -n | \
  awk '{a[NR]=$1} END{n=NR; printf "n=%d p50=%s p95=%s p99=%s max=%s\n",n,a[int(n*0.5)+1],a[int(n*0.95)+1],a[int(n*0.99)+1],a[n]}'

再出图(镜像的入口命令就是 goaccess,别把命令名再写一遍,否则它会把它当成日志文件名):

docker compose exec -T gateway cat /var/log/nginx/lab_combined.log > /tmp/acc_combined.log
docker run --rm -v /tmp:/d allinurl/goaccess:latest /d/acc_combined.log \
  --log-format=COMBINED -o /d/report.html && ls -l /tmp/report.html

实测:分位数 n=109 p50=0.001 p95=0.533 p99=3.016 max=6.009——p50 是 1 毫秒、p99 是 3 秒,说明这条日志里存在「大多数请求毫秒级、极少数吃满超时」的双峰,正是实验 1/2 制造出来的。goaccess 喂 88 行 COMBINED 日志后产出 report.html,其 JSON 输出里 total_requests=88、valid_requests=88、unique_files=6、bandwidth=14776。

坑在喂什么:直接把 lab 的 main 格式喂给它,实测 fatal 退出并报 No time format was found on your conf file.,因为 main 里没有 $time_local;解法要么用第 4 节的 combined_ts 副日志,要么用 --log-format 自己描述(含 %d:%t)。

6. 验收自测(5 题)

先盖住「答案要点」自己写一遍,再逐条对照;答不上的回对应小节重读。

Q1. 日志里出现 504 rt=3.008 urt=1.005, 1.002, 1.002 up=A, B, C,你 30 秒内会先动哪个配置?

答案要点:不是「一次慢 3 秒」,是三次读超时叠加:urt 三段各 ≈proxy_read_timeout,rt≈Σurt。先看 proxy_next_upstream 与 proxy_read_timeout 的取舍,再看三个上游是否整体变慢(up= 显示三个都被试过)。改超时要配 SLA:调小更快失败但误杀慢请求,调大则重试成本成倍放大(3 段就 ×3)。

Q2. 499 0 rt=0.201 urt=0.200 up=172.30.0.3:8080,error_log 里没有对应行。这三件事分别说明什么?

答案要点:499=客户端在响应前断开(nginx 自造码);0 字节说明响应还没开始发;urt=0.200 小于超时值说明上游本身在正常工作(不是上游超时);warn 级 error_log 不记 499,所以只盯 error_log 会漏掉整类「客户端等不及」的问题。动作:查客户端超时/重试设置与网关前排队时长,而不是查应用。

Q3. 停掉全部后端后返回 502 而不是 503,error_log 里会看到哪两种消息,各自意味着什么?

答案要点:开源 Nginx「无可用上游」默认给 502(实测 12/12)。两种消息:connect() failed (111: Connection refused)=连不上(进程没起/端口错),以及 no live upstreams while connecting to upstream=max_fails 把组内成员全摘了(此时 $upstream_addr 是组名 app_pool)。恢复要等 fail_timeout(lab 是 10s),期间不会自动试探。503 一般来自应用自身或 limit_req 的默认 limit_req_status 503。

Q4. 为什么把 lab 的 main 格式日志直接喂 goaccess 会 fatal?给出两种解法。

答案要点:报 No time format was found on your conf file.——main 里没有 $time_local,goaccess 的按日/按小时面板无时间轴可用。解法一:另写一条 log_format combined_ts '... [$time_local] ...' 副日志喂它;解法二:--log-format 自行描述字段(必须含 %d:%t)。前者更省心,代价是多写一份日志(IO 翻倍)。

Q5. 让「网关日志」和「上游应用日志」对上同一个请求,最省事的做法是什么?为什么不用时间戳对?

答案要点:$request_id(≥1.11.0)+ 请求头透传:proxy_set_header X-Request-Id $request_id;,上游把它打进自己的日志(lab 的 app 会把收到的头回显,实测 /api/json 返回的 headers 里 X-Request-Id 与网关 rid= 完全一致)。时间戳对不上的原因是:网关的 $time_local 是响应完成时刻,上游的是请求开始时刻,且同秒多请求、时钟漂移都会让配对失效。注意 rid 只做关联,不能承载业务敏感信息。

7. 常见坑

  1. 线上大量超时,error_log 干净得像没事。现象:用户抱怨慢/超时,日志里搜不到错误。根因:只开 error_log,499 在 warn 级没有记录。正解:以 access_log 为主证据,先用 awk '{n[$7]++} END{for(s in n) print s, n[s]}' lab_access.log 看状态分布。

  2. 三个后端轮流慢,日志里 urt 只有一个值/字段全错位。现象:按空格切字段后列对不上。根因:多值用 ", " 分隔,urt=1.005, 1.002 会被切成 4 个字段。正解:先 gsub(", ", ",") 再按空白切,或整体用 -F'urt=' 取段。

  3. 高 QPS 下磁盘 %util 打满、latency 抖动。现象:请求处理没变慢但整体延迟上台阶。根因:每条日志一次 write,且无 buffer/flush。正解:access_log ... buffer=32k flush=5s;open_log_file_cache 只解决 open 不解决 write;再不行就分流到远端。

  4. goaccess 无数据 / 报表时间轴空白。现象:跑得出 HTML 但面板是空的。根因:main 格式缺 $time_local。正解:加 combined_ts 副日志,或用 --log-format 显式带 %d:%t。

  5. 宿主机 curl /nginx_status 被 403,明明配了 allow 127.0.0.1。现象:容器内能读、宿主读不到。根因:容器端口映射后源 IP 是 Docker 网关(192.168.65.1),不是 127.0.0.1。正解:容器内 docker compose exec -T gateway wget -qO- 127.0.0.1:80/nginx_status;或改成 allow 172.16.0.0/12; 并配 deny all。

  6. lab_5xx.log 里混着 403/404。现象:5xx 看板被 4xx 污染。根因:map 用了 ~^[45]。正解:要纯 5xx 用 ~^5;if= 只把 "0"/空当关闭,default 必须显式写 0。

  7. 以为后端已被摘流,配置也没问题,但请求还在打它。现象:单上游的站点怎么压都只有连接失败。根因:组里只有一个 server 时 max_fails/fail_timeout 被忽略(实测单成员组连续两次都是 connect() failed,不会进 no live upstreams)。正解:多成员才能验证摘流;单成员靠外置探活(第 7 篇、第 14 篇)。

  8. nginx -t 通过但改动没生效。现象:改完 reload,日志格式还是旧的。根因:校验时漏了 -c /etc/nginx/lab/nginx.conf,校验的是镜像自带默认配置。正解:nginx -t -c ... 后再 nginx -s reload(reload 不需要 -c,master 记着自己的路径)。

8. 延伸阅读

文档页解决什么问题
ngx_http_log_modulelog_format/access_log/if=/escape=json 的权威出处,含 $request_id 等变量说明
ngx_core_module · error_logerror_log 指令与级别定义,含 debug 需 --with-debug 的前提
A debugging log想真正拿到 [debug] 行时的编译与开启方式
ngx_http_upstream_modulemax_fails/fail_timeout 的「单成员组被忽略」原文,以及 zone/resolve
ngx_http_proxy_moduleproxy_next_upstream、proxy_*_timeout、$upstream_* 变量的取值语义
ngx_http_stub_status_module四个计数器的准确定义与 Active/Reading/Writing/Waiting
Variables index$request_time、$bytes_sent、$connection_requests 等逐条定义

章节依赖:本篇承接第 5 篇的 upstream 与第 7 篇的摘流语义,把「哪一端慢、慢几次」变成可读的数字;本篇定义的 trace/jsonl 字段会被第 8 篇的缓存命中率观测、第 14 篇的指标看板、第 15 篇的案例卡直接复用;第 10 篇的 499/502 排障继续用同一套证据链。


系列导航:第 1 篇进程模型 → 第 2 篇安装升级 → 第 3 篇配置语法 → 第 4 篇静态站与 location → 第 5 篇反向代理 → 第 6 篇 rewrite 与 server_name → 第 7 篇负载均衡进阶 → 第 8 篇缓存 → 第 9 篇(本篇)日志排障 → 第 10 篇 HTTPS 与安全 → 第 11 篇 Lua 与 OpenResty → 第 12 篇性能调优 → 第 13 篇高可用架构与网关 → 第 14 篇可观测性与工程化 → 第 15 篇故障案例库