NGINX proxy_pass 域名解析問題


    前兩天發現一個問題,當使用proxy_pass的時候,發現域名對應IP是緩存的,這樣一旦VIP變化之后,就會報錯,下面就來詳細分析一下這個問題。

一、問題說明

 location = /test {
     internal;
     no_error_pages;
     proxy_pass_request_headers off;
     proxy_pass 'http://www.taobao.com/test/router/rest';
 }

    大家應該知道,這是向http://www.taobao.com/test/router/rest發送請求,其實是向202.108.250.251發送請求

ping www.taobao.com
PING scorpio.danuoyi.tbcache.com (202.108.250.251): 56 data bytes
64 bytes from 202.108.250.251: icmp_seq=0 ttl=54 time=4.324 ms
64 bytes from 202.108.250.251: icmp_seq=1 ttl=54 time=8.320 ms

    如果在服務的過程中突然www.taobao.com對應的IP變化了(這是非常常見的,因為taobao.com對應多個域名),那么NGINX仍然會訪問以前的IP202.108.250.251,這是為什么吶?下面咱們就來分析一下。

二、HTTP模塊

    打開NGINX的源代碼,搜索proxy_pass,發現在文件:src/http/modules/ngx_http_proxy_module.c實現了這個方法

static char *
ngx_http_proxy_pass(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
......
}

    那么,繼續往下看

    1、url = &value[1]; //獲取url

    2、ngx_memzero(&u, sizeof(ngx_url_t));

    3、plcf->upstream.upstream = ngx_http_upstream_add(cf, &u, 0);

    用gdb分析,發現ngx_http_upstream_add()函數在文件src/http/ngx_http_upstream.c里面。代碼如下:

  4682 ngx_http_upstream_srv_conf_t *
  4683 ngx_http_upstream_add(ngx_conf_t *cf, ngx_url_t *u, ngx_uint_t flags)
............................................................
- 4692 if (ngx_parse_url(cf->pool, u) != NGX_OK) { 3 4693 if (u->err) { 3 4694 ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,"%s in upstream \"%V\"", u->err, &u->url); 3 4696 } 3 4698 return NULL; 3 4699 }
.............................................................

 

    4、ngx_parse_url,它實在文件core/ngx_inet.c里面,下面是調用的順序

  • ngx_parse_url()調用ngx_parse_inet_url()
  • ngx_parse_inet_url()調用ngx_inet_resolve_host()
  • ngx_inet_resolve_host()調用gethostbyname()
  • gethostbyname()函數就是通過域名獲取IP的函數

三、問題解決

    未完,待續。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM