被动健康检查
Nginx自带有健康检查模块:ngx_http_upstream_module,可以做到基本的健康检查,配置如下:
cat demo.conf
upstream cluster{
server 100.100.137.200:80 max_fails=3 fail_timeout=30s;
# max_fails=3 允许的最大失败次数,超过此值后认为服务器不可用
# fail_timeout=30s 服务器被标记为不可用的持续时间,以及超过max_fails后的冷却时间
}
server {
listen 80;
server_name www.demo.com;
location / {
proxy_pass http://cluster;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Nginx只有当有访问时后,才发起对后端节点探测。如果本次请求中,节点正好出现故障,Nginx依然将请求转交给故障的节点,然后再转交给健康的节点处理。所以不会影响到这次请求的正常进行。但是会影响效率,因为多了一次转发,而且自带模块无法做到预警。
主动健康检查(需使用第三方模块)
下载nginx_upstream_check_module模块
wget https://codeload.github.com/yaoweibin/nginx_upstream_check_module/zip/master
unzip master
cd /usr/local/nginx/sbin/
./nginx -V
nginx version: nginx/1.20.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/usr/local/nginx/ --with-http_stub_status_module --with-http_ssl_module --with-pcre
# 重新编译nginx ,命令和 configure arguments:后面显示的一样加--add-module=/usr/local/nginx-1.20.1/nginx_upstream_check_module-master
cd /usr/local/nginx-1.20.1/
./configure --user=www --group=www --prefix=/usr/local/nginx/ --with-http_stub_status_module --with-http_ssl_module --with-pcre --add-module=/usr/local/nginx-1.20.1/nginx_upstream_check_module-master
make
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old
mv objs/nginx /usr/local/nginx/sbin/
cd /usr/local/nginx/sbin/
./nginx -V #查看有无新模块
配置主动健康检查
主动地健康检查,nignx定时主动地去ping后端的服务列表,当发现某服务出现异常时,把该服务从健康列表中移除,当发现某服务恢复时,又能够将该服务加回健康列表中。淘宝有一个开源的实现nginx_upstream_check_module模块
cat demo.conf
upstream cluster {
server 100.100.137.200:80;
check interval=3000 rise=2 fall=5 timeout=1000 type=http;
check_keepalive_requests 100;
check_http_send "HEAD / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
}
server {
listen 80;
server_name www.demo.com;
location / {
proxy_pass http://cluster;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /status {
check_status; # 启用健康状态检查页面,展示所有配置了check指令的上游服务器状态
access_log off;
allow 100.100.137.0/24;
deny all;
}
}
# 配置解释:
check interval=3000 rise=2 fall=5 timeout=1000 type=http;
# interval=3000:每 3000 毫秒(3秒) 主动检查一次后端服务器状态。
# rise=2:连续 2 次 检查成功,才将服务器标记为 健康(alive)(避免偶发性成功误判)。
# fall=5:连续 5 次 检查失败,才将服务器标记为 不健康(down)(避免偶发性失败误判)。
# timeout=1000:每次检查的 超时时间 为 1000 毫秒(1秒),超时未响应视为失败。
# type=http:检查类型为 HTTP(还可以是 tcp 或 ssl_hello)。
check_keepalive_requests 100;
# check_keepalive_requests 100: 在同一个 TCP 连接上复用 100 次 HTTP 健康检查请求(减少连接建立开销)。适用于 HTTP/1.1,需配合 Connection: keep-alive 使用。
check_http_send "HEAD / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
# 定义发送给后端服务器的健康检查请求
check_http_expect_alive http_2xx http_3xx;
# 定义健康的响应条件:当后端返回 HTTP 状态码 2xx 或 3xx 时,认为服务器健康。其他状态码(如 4xx、5xx)或超时/连接失败会触发失败计数。