最近工作中有这方面的需求,upstream是完全动态,由客户端来指定,开始的时候有一些错误,最后通过resolver指定dns服务来完成,具体流程如下。
1. 开始踩坑
nginx的配置如下:
当我发送这种请求:
报了如下错误:
access.log:
127.0.0.1 - - [14/Sep/2017:23:37:10 +0800] "GET / HTTP/1.1" 502 179 "-" "curl/7.29.0"
error.log:
2017/09/14 23:38:31 [error] 25307#25307: *48 no resolver defined to resolve www.baidu.com, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", host: "127.0.0.1:8001" 很明显这个问题说明没有指定resolver导致自定义upstreamwww.baidu.com。
2. 使用resolver定义域名解析
修改之后的nginx配置如下:
这下请求都正常200了:
req:
curl "127.0.0.1:8001/" -H "upstream-host:www.baidu.com" -voa
curl "127.0.0.1:8001/" -H "upstream-host:www.qq.com" -voa
access.log:
127.0.0.1 - - [14/Sep/2017:23:44:01 +0800] "GET / HTTP/1.1" 200 2381 "-" "curl/7.29.0"
127.0.0.1 - - [14/Sep/2017:23:44:07 +0800] "GET / HTTP/1.1" 200 244182 "-" "curl/7.29.0" 3. resolver使用说明
resolver的语法如下:
Syntax: resolver address ... [valid=time] [ipv6=on|off];
Default: —
Context: http, server, location 可以配置多个dns服务,nginx会采用轮询的方式去访问dns服务,nginx会缓存dns对域名解析的结果,缓存的时间由valid指定,ipv6用于显示开启或者关闭ipv6。
resolver_timeout用于指定dns解析的超时时间。
|