一、前言
在现代生产环境中,负载均衡是确保系统高可用性和可扩展性的核心技术。
Nginx 作为轻量级高性能 Web 服务器,与 Keepalived 结合,可轻松实现 高可用负载均衡集群(HA + LB)。
本篇文章将手把手带你在 Red Hat Enterprise Linux 10 上,完整搭建 Nginx + Keepalived 高可用集群,从安装到自动切换全过程均可实地落地。
⚙️ 二、环境准备
|
角色 |
主机名 |
IP 地址 |
系统版本 |
|
Master |
lb-master |
192.168.10.10 |
Red Hat Enterprise Linux 10 |
|
Backup |
lb-backup |
192.168.10.11 |
Red Hat Enterprise Linux 10 |
|
VIP(虚拟IP) |
— |
192.168.10.100 |
— |
确保两台服务器能互通,并关闭防火墙或放行相关端口。
# 临时关闭防火墙
sudo systemctl stop firewalld
sudo systemctl disable firewalld
# 关闭SELinux
sudo setenforce 0
sudo sed -i 's/^SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
三、安装 Nginx
1. 添加 Nginx 源并安装
sudo dnf install -y nginx
2. 设置 Nginx 开机自启
sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx
3. 修改测试页面内容(区分主从节点)
echo “<h1>Welcome to LB-Master Node</h1>” | sudo tee /usr/share/nginx/html/index.html
在 Backup 节点上修改为:
echo “<h1>Welcome to LB-Backup Node</h1>” | sudo tee /usr/share/nginx/html/index.html
访问 http://192.168.10.10 与 http://192.168.10.11,确认页面正常。
四、安装 Keepalived
1. 安装 Keepalived
sudo dnf install -y keepalived
2. 主节点配置文件
/etc/keepalived/keepalived.conf
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 50
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1234
}
virtual_ipaddress {
192.168.10.100
}
track_script {
chk_nginx
}
}
vrrp_script chk_nginx {
script “/etc/keepalived/check_nginx.sh”
interval 2
weight -2
}
3. 备节点配置文件
/etc/keepalived/keepalived.conf
vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 50
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1234
}
virtual_ipaddress {
192.168.10.100
}
track_script {
chk_nginx
}
}
vrrp_script chk_nginx {
script “/etc/keepalived/check_nginx.sh”
interval 2
weight -2
}
五、Nginx 健康检查脚本
创建
/etc/keepalived/check_nginx.sh
#!/bin/bash
if ! systemctl is-active –quiet nginx; then
systemctl restart nginx
sleep 2
if ! systemctl is-active –quiet nginx; then
systemctl stop keepalived
fi
fi
授权:
sudo chmod +x /etc/keepalived/check_nginx.sh
六、启动 Keepalived
分别在两台节点执行:
sudo systemctl enable keepalived
sudo systemctl start keepalived
sudo systemctl status keepalived
七、验证高可用效果
- 查看虚拟 IP:
ip addr show | grep 192.168.10.100
- 应出目前主节点上。
- 停止主节点的 Nginx 服务:
sudo systemctl stop nginx
- 查看 VIP 是否自动漂移至备节点:
ip addr show | grep 192.168.10.100
- 当主节点恢复后:
sudo systemctl start nginx
- VIP 将自动回切。
八、系统优化提议
|
优化项 |
命令 |
说明 |
|
优化系统最大文件数 |
ulimit -n 65535 |
防止高并发连接导致文件句柄不足 |
|
开启Nginx多进程 |
worker_processes auto; |
提升并发性能 |
|
调整TCP连接参数 |
修改 /etc/sysctl.conf |
提升网络吞吐 |
|
开启防火墙白名单 |
firewall-cmd –permanent –add-service=http |
仅允许HTTP/HTTPS流量 |
九、总结
本文从零开始搭建了一个 Nginx + Keepalived 高可用负载均衡集群,并实现了 自动故障切换与恢复。
通过这种方式,你可以在任何 Red Hat Linux 10 环境中快速部署高可用架构,为业务稳定运行保驾护航。

收藏了,感谢分享