严格来说,nginx到目前为止没有针对负载均衡后端节点的健康检测的模块,但是可以通过upstream负载均衡组中的max_fails=number和fail_timeout=time来间接实现,但还是会把请求转发给故障服务器的,然后再转发给别的服务器,这样就需要多一次转发。nginx_upstream_check_module为淘宝技术团队开发的nginx模块,用来检测后端服务器的健康状态,如果后端服务器不可用,则请求不再转发到这台服务器。
官网: https://github.com/yaoweibin/nginx_upstream_check_module
0x01: 安装nginx_upstream_check_module模块
以下命令均在root用户下执行
wget https://github.com/yaoweibin/nginx_upstream_check_module/archive/refs/tags/v0.4.0.tar.gz
进入nginx源码目录,进行打该模块的补丁(这一步千万不能遗漏)
在nginx-1.22.0目录执行如下命令,nginx_upstream_check_module源码目录跟nginx源码目录同级
patch -p1 < /usr/local/src/nginx_upstream_check_module-0.4.0/check_1.20.1+.patch
然后通过./configure --add-module来增加模块
./configure --prefix=/usr/local/nginx-1.22.0/ --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --with-http_gzip_static_module --with-http_stub_status_module --with-http_ssl_module --user=www --group=www --add-module=/usr/local/src/nginx_upstream_check_module-0.4.0
0x02:配置nginx upstream参数
upstream testserver {
server 192.168.159.161:80;
server 192.168.159.162:80;
check interval=1000 rise=3 fall=3 timeout=500 type=http;
check_http_send "HEAD / HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
interval: 向后端发送的健康检查包的间隔,单位为毫秒
rise: 如果连续成功次数达到rise_count,服务器就被认为是up
fall: 如果连续失败次数达到fall_count,服务器就被认为是down
timeout: 后端健康请求的超时时间,单位为毫秒
type: 健康检查包的类型,支持tcp、ssl_hello、http、mysql、ajp
- 如果想查看后端服务器实时的健康状态,可以在对应server中增加以下location配置
location /upstatus {
check_status;
access_log off;
#allow SOME.IP.ADD.RESS;
#deny all;
}
0x03:查看健康检查状态
通过http://192.168.159.160/upstatus 页面查看