Nginx 提供了一个强大的负载均衡机制,可以用于在多个后端服务器之间分配请求,以提高网站的可用性和响应速度。
在Nginx官方模块提供的模块中,没有对负载均衡后端节点的健康检查模块,但可以使用第三方模块。 nginx_upstream_check_module
来检测后端服务的健康状态
nginx_upstream_check_module 是一个非常实用的 Nginx 第三方模块,它可以为我们提供主动的健康检查功能,有效地提高后端服务器的可用性和稳定性。
1.前置准备
#安装编译命令
yum install -y gcc glibc gcc-c++ pcre-devel openssl-devel patch
#下载源码包和模块包
wget http://nginx.org/download/nginx-1.24.0.tar.gz
https://github.com/yaoweibin/nginx_upstream_check_module/archive/refs/heads/master.zip
2.解压并将模块包添加nginx中
#解压
tar xf nginx-1.24.0.tar.gz
unzip nginx_upstream_check_module-master.zip
[root@lb01 ~]# cd nginx-1.24.0/
打补丁: 添加新的模块到nginx中
[root@lb01 nginx-1.24.0]# patch -p1 < ../nginx_upstream_check_module-master/check_1.20.1+.patch
3.配置参数
[root@lb01 nginx-1.24.0]# ./configure --prefix=/etc/nginx \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--with-http_ssl_module \
--add-module=/root/nginx_upstream_check_module-master
# --prefix 指定nginx 的安装目录
# --sbin-path 运行命令
# --add-module 添加模块的目录
4. 编译安装
[root@lb01 nginx-1.24.0]# make && make install
#检查第三方模块包是否安装成功
[root@lb01 nginx-1.24.0]# nginx -V
5.验证健康检查模块功能
在已有的负载均衡上增加健康检查的功能
[root@lb01 conf.d]# cat proxy_web.conf
upstream webs {
server 172.16.1.7:80 max_fails=2 fail_timeout=10s;
server 172.16.1.8:80 max_fails=2 fail_timeout=10s;
check interval=3000 rise=2 fall=3 timeout=1000 type=tcp;
#interval 检测间隔时间,单位为毫秒
#rise 表示请求2次正常,标记此后端的状态为up
#fall 表示请求3次失败,标记此后端的状态为down
#type 类型为tcp
#timeout 超时时间,单位为毫秒
check_http_send "HEAD /api/tTag/queryTag HTTP/1.0\r\n\r\n";
check_http_expect_alive http_2xx http_3xx;
#check_http_send 定义了发送给后端服务器的检查请求。
#check_http_expect_alive 指定哪些 HTTP 状态码会被认为是“存活”的。
}
server {
listen 80;
server_name blog.liux.com;
location / {
proxy_pass http://webs;
include proxy_params; #请求时携带的参数配置
}
location /upstream_check {
check_status;
}
}
[root@lb01 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@lb01 conf.d]# systemctl restart nginx
访问: blog.liux.com/upstream_check 会监测到两台服务器的健康状态情况,如其中一台down掉,会自动剔除。恢复正常后也会加入