Nginx根据http层状态健康检查

100人浏览   2024-08-05 10:17:19

Nginx是一个很强大的中间件,在做负载均衡的时候,通常是通过IP:Port的形式来实现,有时候是服务器及进程没有问题,但程序假死,如果还继续分压,就会出错,这个时候就需要真正探测程序是否能提供服务为阈值来判断比较准确。

一、项目上用的Nginx做的负载均衡,但发现有时候服务已经死掉或者不提供服务,进程还在,比如内存溢出(OOM)的时候,就是这个现象,但Nginx是通过IP:port来负载的,这个时候,如果继续往已经挂掉的服务分配负载,就会出现服务不能访问的错误,所以,我们得根据服务的状态来判断,不能根据ip:port的形式,要实现这个功能,需要用到Nginx第三方模块
nginx_upstream_check_module,解压后如下

  • 解压后进行编译安装:
280  2021-12-01 12:22:47 cd nginx-1.14.0/
283  2021-12-01 12:23:21 patch -p1 < /cmp/soft/nginx_upstream/nginx_upstream_check_module-master/check_1.14.0+.patch
284  2021-12-01 12:23:43 /cmp/nginx/sbin/nginx -V
286  2021-12-01 12:24:32 ./configure --prefix=/cmp/nginx --user=cmspvbs --group=cmspvbs --with-http_realip_module --with-http_stub_status_module 
287  2021-12-01 12:24:52 ./configure --add-module=/path/to/nginx_http_upstream_check_module
288  2021-12-01 12:26:06 ./configure --add-module=/cmp/soft/nginx_upstream/nginx_upstream_check_module-master
289  2021-12-01 12:26:26 make 
290  2021-12-01 12:27:18 make install

二、Nginx配置

http {
    upstream cmc_booters {
      # This is cmp simple round-robin
      server  180.2.32.170:18091;
      server  180.2.32.171:18091;

      # This is check options
      check interval=5000 rise=1 fall=3 timeout=3000 type=http;
      check_http_send "HEAD /status HTTP/1.1\r\nHOST:127.0.0.1\r\nConnection:keep-alive\r\n\r\n";
    }

    server {
        location /proxy_status {
	    check_status;
	    access_log on;
	    allow all;
	}
    }
}
  • - check_status:[html|csv|json],默认html
  • -check_http_send:指定检测的http访问地址,默认/
  • - type:[tcp|http|ssl_hello|mysql|ajp],默认tcp
  • - interval:向后端发送的健康检查包的间隔,单位(毫秒)
  • - fall(fall_count): 如果连续失败次数达到fall_count,服务器就被认为是down。
  • - rise(rise_count): 如果连续成功次数达到rise_count,服务器就被认为是up。
  • - timeout: 后端健康请求的超时时间。
  • - host:本机IP地址。

我在使用的时候是忘记host设置,一直监测不到服务的状态,网上的教程很多也没有些,需留一下

三、重启Nginx,使配置生效

./sbin/nginx -s reload


Nginx生效后可以通过配置中的/proxy_status查看状态

  • 这个功能非常有用,在实际场景中也经常用到,服务进程存在,但由于各种原因已经不提供服务,通过IP:port这种4层协议是监测不到的,根据http7层协议更准确

相关推荐