Nginx 是一款高性能的Web服务器和反向代理服务器,但是在实际应用中,后端服务器的故障或者宕机是不可避免的。为了提高服务的可靠性和稳定性,我们需要对后端服务器进行健康检查,及时检测到故障并进行处理。本文将介绍一个基于 Nginx 的第三方模块 nginx_upstream_check_module,它可以实现 Nginx 的主动健康检查功能,可以帮助我们更加有效地管理后端服务器。
架构说明
架构中的IP是我本地虚拟机的IP
版本说明
- nginx 1.20.2
- nginx_upstream_check_module 0.4.0
模块简介
nginx_upstream_check_module 是一个 Nginx 的第三方模块,它可以实现 Nginx 的主动健康检查功能。该模块可以定期向后端服务器发送 HTTP 请求,检测后端服务器的健康状况,并根据检测结果动态地调整负载均衡策略,从而保证后端服务器的可用性和稳定性
准备工作
- 下载nginx 1.20.2并解压
# 下载
wget https://nginx.org/download/nginx-1.20.2.tar.gz
# 解压
tar zxvf nginx-1.20.2.tar.gz
下载 nginx_upstream_check_module,并解压
如下图所示,下载v0.4.0
下载完成后解压
# 解压
tar zxvf nginx_upstream_check_module-0.4.0.tar.gz
下载nginx 1.20.2的补丁文件,下载地址:check_1.20.1+.patch
如下图所示,3份文件下载解压完成
模块安装
给nginx 1.20.2打补丁
# 安装patch,如果已经安装不需要执行这一步
yum install patch
# 切换到你解压好的nginx文件夹下
cd /root/judith/nginx-1.20.2
# 打补丁
patch -p1 < /root/judith/patch_1.20.1.patch
configure nginx
# 切换到你解压好的nginx文件夹下
cd nginx-1.20.2
# --prefix: 配置nginx的安装路径
# --add-module: 是你下载解压后的nginx_upstream_check_module-0.4.0路径
./configure --prefix=/usr/local/nginx20 --add-module=/root/judith/nginx_upstream_check_module-0.4.0
安装nginx
make
make install
验证nginx是否安装成功
# 检查nginx配置文件是否正确
/usr/local/nginx20/sbin/nginx -t
# 启动nginx server
/usr/local/nginx20/sbin/nginx
# 访问nginx server
curl localhost:80
输出如下,说明nginx安装成功,并可以成功启动
模块使用
安装和配置好 nginx_upstream_check_module 之后,即可使用该模块进行健康检查。当后端服务器发生故障或者宕机时,该模块会自动将该服务器从负载均衡池中移除,直到该服务器恢复正常工作。
配置nginx
配置文件nginx.conf的路径为:/usr/local/nginx20/conf/nginx.conf,其中
/usr/local/nginx20
是安装nginx时的配置路径
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream httpget {
server 192.168.91.133:80;
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;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://httpget;
root html;
}
location /status {
check_status;
access_log off;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
其中,check 指令用于配置健康检查的参数,interval 表示检查间隔时间,rise 表示连续成功次数,fall 表示连续失败次数,timeout 表示超时时间,type 表示检查类型。check_http_send 和 check_http_expect_alive 用于配置健康检查的请求头和响应码。
重启nginx服务
# 检查nginx配置文件是否正确
/usr/local/nginx20/sbin/nginx -t
# 重启nginx server
/usr/local/nginx20/sbin/nginx -s reload
在浏览器访问nginx服务
我的地址是: http://192.168.91.134:80
出现以上问题,是因为我的集群中的服务器 192.168.91.133 这个虚拟机启动服务
启动集群中服务器192.168.91.133的服务后,再访问nginx反向代理
总结
nginx_upstream_check_module 是一个非常实用的 Nginx 第三方模块,它可以为我们提供主动的健康检查功能,有效地提高后端服务器的可用性和稳定性。在实际应用中,我们可以根据自己的需求来配置检查参数,实现最佳的负载均衡策略。