作者:手机用户2702932821 | 来源:互联网 | 2023-09-16 10:01
这里我们采用两台Nginx服务器作为前端,一主一从,Keepalived实现状态监测,保证Nginx正常对外提供服务,即主Nginx服务进程死掉之后,keepalived能够通过其自身的检测机制
这里我们采用两台Nginx服务器作为前端,一主一从,Keepalived实现状态监测,保证Nginx正常对外提供服务,即主Nginx服务进程死掉之后,keepalived能够通过其自身的检测机制将网站的访问切换到从Nginx上来。
主服务器IP:192.168.1.217
从服务IP:192.168.1.218
虚IP:192.168.1.219
你可以将你网站域名解析到 192.168.1.219 对应的公网IP上,这样主从服务器可以轮流接管该虚IP,保证网站正常对外提供访问
- 安装nginx
- 安装keepalived
- 配置keepalived
配置nginx-001服务器
cp /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.bak
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id nginx_server_1
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2
weight 20
!weight为正数
!如果脚本执行结果为0,,Master:weight+priority>Backup:weight+priority(不切换)
!如果脚本执行结果不为0,Master:priority:priority+weight(切换)
!weight为负数
!如果脚本执行结果为0,,Master:priority>Backup:priority(不切换)
!如果脚本执行结果不为0,Master:priority+weight:priority(切换)
!一般来说,weight的绝对值要大于Master和Backup的priority之差
}
vrrp_instance VI_1 {
state MASTER
interface eno16777984
virtual_router_id 51
mcast_src_ip 192.168.1.217
priority 100
nopreempt
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.1.219/24
}
}
vim /etc/keepalived/nginx_check.sh
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ];then
/usr/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
chmod +xxx /etc/keepalived/nginx_check.sh
cp /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.bak
vim /etc/keepalived/keepalived.conf
(注意:
state 和主不一样,是BACKUP
route_id 和主不一样
priority 小于主机
)
! Configuration File for keepalived
global_defs {
router_id nginx_server_2
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 2
weight 20
!weight为正数
!如果脚本执行结果为0,,Master:weight+priority>Backup:weight+priority(不切换)
!如果脚本执行结果不为0,Master:priority:priority+weight(切换)
!weight为负数
!如果脚本执行结果为0,,Master:priority>Backup:priority(不切换)
!如果脚本执行结果不为0,Master:priority+weight:priority(切换)
!一般来说,weight的绝对值要大于Master和Backup的priority之差
}
vrrp_instance VI_1 {
state BACKUP
interface eno16777984
virtual_router_id 51
mcast_src_ip 192.168.1.218
priority 90
nopreempt
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.1.219/24
}
}
- 启动keepalived
systemctl start keepalived
systemctl enable keepalived
- 测试keepalived+nginx的主从
- 在主机上 ip a ,查看192.168.1.219成功绑定。
- shutdown主机,查看从机192.168.1.219成功绑定。说明vip成功漂移