本文仅对代理流程做简要解读。
首先先看下大概的配置:
upstream proxy_server{
server localhost:8082 weight=3;
server localhost:8083 weight=1;
}
server{
listen localhost:8081;
server_name www.a.com www.b.com *.c.com;
location /proxy {
proxy_pass http://proxy_server;
}
}
使用upstream和proxy_pass配置时,解析配置的流程可参考NGINX源码之:模块配置解析(1)
这里主要看下upstream 和proxy_pass 两个配置,其他的相关的配置可参考Module ngx_http_upstream_module、Module ngx_http_proxy_module
1、ngx_http_upstream
在解析upstream配置时进入ngx_http_upstream方法:
在upstream块中的解析,主要是对server配置的解析:
2、ngx_http_proxy_pass
在解析proxy_pass配置时,进入ngx_http_proxy_pass方法:
完成初始化后,那么接下来就看请求进来的时候,怎么执行到ngx_http_proxy_handler了。
NGINX通过epoll机制监听请求,过程可参考NGINX源码之:event与epoll、请求处理,可以参考NGINX源码之:请求处理、同时设计请求处理的11个阶段,可以参考NGINX源码之:phase与handlers
在请求处理ngx_http_core_find_config_phase阶段、通过请求的uri匹配对应的location配置,再通过ngx_http_update_location_config设置content处理阶段的handler:
这里的clcf->handler,就是上面解析proxy_pass时,设置的ngx_http_proxy_handler。当执行到NGX_HTTP_CONTENT_PHASE阶段时:
优先使用设置的handler执行。
3、ngx_http_proxy_handler
在该方法中,主要看ngx_http_read_client_request_body():
这里就不对round_robin_peer机制做解读了。有兴趣可自行深入了解。
在NGINX中默认使用ngx_http_upstream_get_round_robin_peer获取upstream中的配置的某个server。也可通过配置hash、ip_hash、least_conn、random、keepalive等指定获取peer的算法。
具体配置方法可以参考peer获取算法设置