nginx -t 无法发现 resolver 缺失问题,因其仅校验语法而非运行时DNS配置;resolver缺失导致的解析慢属行为缺陷,须结合error.log中resolving日志、proxy_pass是否含变量、resolver作用域位置及dig/ss工具交叉验证。

直接运行 nginx -t 无法发现 resolver 缺失问题,因为语法检查不验证 DNS 配置是否合理或是否存在——它只检查指令格式、括号匹配和基本上下文。resolver 未配置导致的域名解析慢,属于运行时行为缺陷,必须结合日志、网络工具和配置逻辑交叉验证。
看 error.log 是否出现阻塞式解析痕迹
开启 Nginx 错误日志为 error_log /var/log/nginx/error.log debug;(需编译含 --with-debug),然后发请求观察:
- 若看到
resolving "api.example.com"但长时间无resolved to x.x.x.x日志,说明 DNS 查询卡住或未触发异步解析 - 若反复出现
connect() failed (111: Connection refused) while connecting to upstream,且后端实际在线,大概率是 resolver 缺失 + proxy_pass 写死域名,Nginx 正在用系统默认或不可用 DNS 同步阻塞查询 - 若日志里压根没出现
resolving字样,说明 Nginx 根本没走运行时解析路径——基本可断定:proxy_pass 没用变量,或 resolver 不在有效作用域
查配置中 proxy_pass 是否写死域名
搜索所有 proxy_pass 指令,重点识别以下写法:
-
proxy_pass http://api.example.com;→ ❌ 静态解析,启动时查一次,永不更新,resolver 配了也无效 -
proxy_pass https://oss-cn-shanghai.aliyuncs.com/;→ ❌ 同上,尤其 HTTPS 场景还可能因 SNI 缺失直接失败 -
set $upstream "api.example.com"; proxy_pass http://$upstream;→ ✅ 触发 resolver 解析,前提是 resolver 已声明
确认 resolver 是否落在正确位置且生效
resolver 不继承、不全局默认,必须出现在能触发动态解析的上下文中:
- HTTP 反向代理:必须在
http块顶层,或至少在包含变量式proxy_pass的server/location块内显式写出 - 正向代理或 stream 四层代理:resolver 必须写在对应
server或location块内,http块里的配置不生效 - 执行
nginx -T | grep resolver,确认输出中 resolver 出现在实际使用变量的 location 所属层级
用 dig 和 ss 辅助交叉验证
仅靠配置文件看不出 resolver 是否真起作用,要观察真实行为:
- 用
dig @223.5.5.5 api.example.com +short测试 DNS 延迟,若超过 200ms,说明上游 DNS 本身慢,resolver_timeout 应设为 4–5s 而非盲目调大 - 请求发出后,立刻执行
ss -tnp | grep :8080(假设后端端口是 8080),看连接目标 IP 是否变化;若始终连同一个旧 IP,说明 resolver + 变量未配合成功 - 临时把 resolver 改成一个不可达地址(如
resolver 192.0.2.1 valid=30s;),再发请求——若在 5 秒左右报 502 且 error.log 显示resolving timed out,说明 resolver_timeout 已生效;否则就是根本没走 resolver 路径


















