数码资讯
利用Nginx的resolver实现动态upstream
选购提示
关注价格、性能、续航、售后和真实使用场景,理性比较后再下单。
之前写了篇文章用openresty实现了一个动态路由,虽然说是动态的,但是实际上还是需要将upstream在配置文件中写好,还是相当于静态的。
最近工作中有这方面的需求,upstream是完全动态,由客户端来指定,开始的时候有一些错误,最后通过resolver指定dns服务来完成,具体流程如下。
1. 开始踩坑
nginx的配置如下:
worker_processes 1; events { worker_connections 1024; } http { server { listen 8001; server_name localhost; location / { set $upstream_host $http_upstream_host; echo $http_upstream_host; proxy_pass http://$upstream_host; } } }
当我发送这种请求:
curl "127.0.0.1:8001/" -H "upstream-host:www.baidu.com" -v
报了如下错误:
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配置如下:
worker_processes 1; events { worker_connections 1024; } http { resolver 114.114.114.114; server { listen 8001; server_name localhost; location / { set $upstream_host $http_upstream_host; echo $http_upstream_host; proxy_pass http://$upstream_host; } } }
这下请求都正常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。
Syntax: resolver_timeout time; Default: resolver_timeout 30s; Context: http, server, location
resolver_timeout用于指定dns解析的超时时间。
4. ref
http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver
声明:本文内容用于数码产品信息整理与选购参考,具体价格、库存、售后政策以官方渠道和电商页面实时信息为准。