默认情况下nginx做反向代理,如果后端服务器宕掉的话,nginx是不能把这台服务器踢除upstream的;以还会根据超时间隔来发送请求转发到这台服务器上面去;借助网上开源的nginx模快nginx_upstream_check_module来检测后方服务器的健康状态,当后端服务器不可用,则不转发到这台服务器。
原来的我配置:
upstream www_server {
server 10.0.10.13:80 weight=1 max_fails=2 fail_timeout=30s;
server 10.0.10.14:80 weight=1 max_fails=2 fail_timeout=30s;
}
这是没有添加nginx_upstream_check_module
模块前的配置,这样配置了后端服务器挂掉后就会每30秒再转发一次到这台宕掉的机器上,虽然很快但是还是浪费了一次请求时间;并且是不断的循环,间隔就是30秒,并不会有max_fails=2
的说法;而添加模块后,如果后端服务器宕机了,就不再转发到这宕掉的机器上;
Nginx添加后端健康状态检查
下载补丁并解压:
wget https://codeload.github.com/yaoweibin/nginx_upstream_check_module/zip/master
tar xf nginx-1.8.1.tar.gz
unzip nginx_upstream_check_module-master.zip
打上补丁:
cd nginx-1.8.1
patch -p1 <../nginx_upstream_check_module-master/check_1.7.2+.patch
重新编译:
./configure \
--prefix=/usr/local/nginx-1.8.1 \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--http-log-path=/var/log/nginx/access.log \
--error-log-path=/var/log/nginx/error.log \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-http_realip_module \
--with-http_stub_status_module \
--add-module=../nginx_upstream_check_module-master
make && make install
conf.d/default.conf 配置信息:
upstream w5xx {
#主节点C
server 10.0.10.80:8180;
server 10.0.10.80:8280;
#备用节点D
server 10.0.10.80:8380 backup;
#nginx_upstream_check_module功能配置:
check interval=5000 rise=2 fall=2 timeout=3000; #说明:
#interval 5秒对各个节点做一次80端口探测
#rise 2次成功,节点可用,则 接受正式请求
#fall 2次失败,节点剔除,则不接受正式请求
#timeout 1次探测的网络连接超时时间
}
server {
listen 80;
server_name ceshi.5xx.com;
root /var/www/html/;
#代理连接超时时间
proxy_connect_timeout 5;
#代理传输超时时间
proxy_read_timeout 15;
#节点健康状态展示页面
location /status {
check_status;
access_log off;
}
location / {
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_pass http://w5xx;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
access_log /var/log/nginx/access.log proxy;
}
当有一个节点宕机后,通过url可以观察到状态已经变化了;
上面的generation:10 表示Nginx服务reload或重启过10次,这是自配置这个健康模块后开始记录;
通过监控Nginx的日志可以看到也不再转发请求到8180端口了;
这就是我想要的效果。