DEBUG.WIKI
RackNerd;$21.99/年 · 1GB KVM
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →
腾讯云;让你的想法跑起来;轻量服务器 · 建站 / Docker / API;查看产品 →

解决 Nginx 报错 could not be resolved 上游域名解析失败修复

排查 Nginx 代理外部域名抛出 xxx.com could not be resolved (3: Host not found) 错误,配置 resolver 指令与动态变量解析。

问题现象

在 Nginx 的 proxy_pass 中配置了动态上游域名,启动或收到请求时报错:

2026/11/15 12:00:00 [error] 1234#1234: *1 
api.partner.com could not be resolved (3: Host not found), 
client: 198.51.100.1, server: example.com, 
request: "GET /gateway HTTP/1.1"

触发根因

  1. Nginx 内部没有配置 resolver DNS 解析器:在配置中使用包含变量的 proxy_pass http://$backend 时,Nginx 强制要求必须在配置中显式声明用于域名解析的 DNS 服务器;
  2. DNS 缓存 TTL 到期但在启动时静态绑死。

解决步骤

1. 在配置中声明 resolver 指令并设置缓存有效时长

编辑 Nginx 配置文件:

location /gateway {
    # 声明可靠的 DNS 服务器(例如内网 DNS 或公共 DNS),缓存 30 秒更新一次
    resolver 8.8.8.8 1.1.1.1 valid=30s ipv6=off;
    resolver_timeout 5s;

    # 使用变量避免 Nginx 在启动时静态解析并死锁 IP
    set $upstream_endpoint https://api.partner.com;
    proxy_pass $upstream_endpoint;
    
    proxy_set_header Host api.partner.com;
}

2. 重载 Nginx 服务

sudo nginx -s reload

验证确认

再次发起请求验证:

curl -I http://example.com/gateway

控制台成功打印目标 API 的正常返回响应,域名动态解析工作稳定。