检查后端状态 后端如果出现故障或down机,如何不让他请求故障服务器,有时候存在down了也还继续请求的现象

采用第三方模块:

nginx_upstream_check_module (淘宝)
https://github.com/yaoweibin/nginx_upstream_check_module
healthcheck_nginx_upstreams (自带)
https://github.com/cep21/healthcheck_nginx_upstreams

下载:
wget https://codeload.github.com/yaoweibin/nginx_upstream_check_module/zip/master

导入步骤:

unzip ./nginx_upstream_check_module-master.zip 注意是将补丁打入Nginx源码,不是Nginx的安装路径: 根据版本,选择check版本

导入前提示:

If you use nginx-1.2.1 or nginx-1.3.0, the nginx upstream round robin
module changed greatly. You should use the patch named
'check_1.2.1.patch'.
If you use nginx-1.2.2+ or nginx-1.3.1+, It added the upstream
least_conn module. You should use the patch named 'check_1.2.2+.patch'.
If you use nginx-1.2.6+ or nginx-1.3.9+, It adjusted the round robin
module. You should use the patch named 'check_1.2.6+.patch'.
If you use nginx-1.5.12+, You should use the patch named
'check_1.5.12+.patch'.
If you use nginx-1.7.2+, You should use the patch named
'check_1.7.2+.patch'.

正式导入

# yum install patch -y
# cd ./nginx-1.13.9
# sed -i -e 's/1.6.2/2.0/g' -e 's/nginx\//LXS/g' -e 's/"NGINX"/"LXS"/g' src/core/nginx.h 
# patch -p1 < ../nginx_upstream_check_module-master/check_1.12.1+.patch 

成功:输入信息,如果出现FAIL表示错误

patching file src/http/modules/ngx_http_upstream_ip_hash_module.c
patching file src/http/modules/ngx_http_upstream_least_conn_module.c
patching file src/http/ngx_http_upstream_round_robin.c
patching file src/http/ngx_http_upstream_round_robin.h

编译nginx:

./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_ssl_module    --add-module=../nginx_upstream_check_module-master/

配置负载均衡:

upstream cluster {
# simple round-robin
server 192.168.2.128:80;
server 192.168.2.129:80;
check interval=5000 rise=1 fall=3 timeout=4000;
#check interval=3000 rise=2 fall=5 timeout=1000 type=ssl_hello;
#check interval=3000 rise=2 fall=5 timeout=1000 type=http;
#check_http_send "HEAD / HTTP/1.0\r\n\r\n";
#check_http_expect_alive http_2xx http_3xx;
}

上面的代码中,check部分就是调用nginx_upstream_check_module模块的语法:

check interval=milliseconds [fall=count] [rise=count]
[timeout=milliseconds] [default_down=true|false]
[type=tcp|http|ssl_hello|mysql|ajp|fastcgi]

interval:必要参数,检查请求的间隔时间。
fall:当检查失败次数超过了fall,这个服务节点就变成down状态。
rise:当检查成功的次数超过了rise,这个服务节点又会变成up状态。
timeout:请求超时时间,超过等待时间后,这次检查就算失败。	default_down:后端服务器的初始状态。默认情况下,检查功能在Nginx启动的时候将会把所有后端节点的状态置为down,检查成功后,在置为up。
type:这是检查通信的协议类型,默认为http。以上类型是检查功能所支持的所有协议类型。

加入健康检查状态:

	location /nstatus {
		check_status;
		access_log off;
		#allow SOME.IP.ADD.RESS;
		#deny all;
		}