1.准备工作
- 两台 CentOS 服务器(主备模式)
- 服务器处于同一网段,可相互 ping 通
2.安装 nginx
具体步骤参见:CentOS 安装 Nginx_番茄烩土豆的博客-CSDN博客
3.关闭防火墙
systemctl stop firewalld.service
4.安装 keepalived
yum install -y keepalived
5.配置 keepalived
vim /etc/keepalived/keepalived.conf
- 配置MASTER
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id master # master为hostname,主机标识
}
vrrp_script chk_nginx {
script "/etc/keepalived/chk_nginx.sh" # 检测脚本
interval 2 # 执行脚本间隔 2s
weight -30 # 本服务器宕机后权重减少 -30
}
vrrp_instance VI_1 {
state MASTER # MASTER主服务器,BACKUP备份服务器
interface enp0s3 # 网卡
virtual_router_id 51 # 虚拟路由ID,主备必须一致
priority 100 # 优先级,即权重
advert_int 1 # 服务器心跳 1s 检测一次
authentication {
auth_type PASS # 认证方式
auth_pass 1111 # 密码
}
virtual_ipaddress {
192.168.0.140 # 虚拟地址,可多个
}
}
- 配置BACKUP
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id node # node为hostname,主机标识
}
vrrp_script chk_nginx {
script "/etc/keepalived/chk_nginx.sh" # 检测脚本
interval 2 # 执行脚本间隔 2s
weight -30 # 本服务器宕机后权重减少 -30
}
vrrp_instance VI_1 {
state BACKUP # MASTER主服务器,BACKUP备份服务器
interface enp0s3 # 网卡
virtual_router_id 51 # 虚拟路由ID,主备必须一致
priority 80 # 优先级,即权重
advert_int 1 # 服务器心跳 1s 检测一次
authentication {
auth_type PASS # 认证方式
auth_pass 1111 # 密码
}
virtual_ipaddress {
192.168.0.140 # 虚拟地址,可多个
}
}
6.nginx 检测脚本
检测脚本地址:chk_nginx.sh-Linux文档类资源-CSDN下载【作者分享,不收$】chk_nginx.sh-Linux文档类资源-CSDN下载
将下载的脚本放到两台服务器的 /etc/keepalived/ 目录下即可
7.启动 keepalived
systemctl start keepalived.service
8.测试
# 1. 浏览器地址栏中输入虚拟地址(vip): 192.168.0.140
# 2. 出现 nginx 起始页,表示 MASTER 搭建成功
# 3. 关闭 MASTER 服务器
systemctl stop keepalived.service
# 4. 继续执行第一步,浏览器地址栏中输入虚拟地址(vip)
# 5. 出现 nginx 起始页,表示 BACKUP 搭建成功