一、环境
Server1:192.168.163.128
[root@localhost ~]# hostnamectl set-hostname server1
Server2:192.168.163.132
[root@localhost ~]# hostnamectl set-hostname server2
VIP:192.168.163.140
二、创建etc下的keepalived目录,编辑配置文件
(一)安装keepalived
[root@server1 ~]# yum -y install keepalived
(二)在etc/keepalived/keepalived.conf中配置:
[root@server1 ~]# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id 1 #设备在组中的标识,设置不一样即可
}#vrrp_script chk_nginx { #健康检查
# script "/etc/keepalived/ck_ng.sh" #检查脚本
# interval 2 #检查频率.秒
# weight -5 #priority减5
# fall 3 #失败三次
# }vrrp_instance VI_1 { #VI_1。实例名两台路由器相同。同学们要注意区分。
state MASTER #主或者从状态
interface ens33 #监控网卡
mcast_src_ip 192.168.163.128 #心跳源IP
virtual_router_id 55 #虚拟路由编号,主备要一致priority 100 #优先级
advert_int 1 #心跳间隔
authentication { #秘钥认证(1-8位)
auth_type PASS
auth_pass 123456
}virtual_ipaddress { #VIP
192.168.163.140/24
}# track_script { #引用脚本
# chk_nginx
# }}
(三)keepalived启动并开机自启
[root@server1 ~]# systemctl start keepalived.service
[root@server1 ~]# systemctl enable keepalived.service
(四)发现server1主机上已有VIP:192.168.163.140
[root@server1 ~]# ip a
(五)给另一台主机server2拷贝一份keepalived.conf
[root@server1 ~]# scp -r /etc/keepalived/keepalived.conf 192.168.163.135:/etc/keepalived/
1.修改server1拷贝的keepalived.conf:
router_id 2 #设备在组中的标识,设置不一样即可
state BACKUP #从状态
mcast_src_ip 192.168.163.132 #心跳源IP
priority 99 #优先级
#主机server1 keepalived的其他配置server2
三、安装Nginx
(一)yum安装并开机自启:
[root@server1 ~]# yum -y install nginx
[root@server1 ~]# systemctl start nginx.service
[root@server1 ~]# systemctl enable nginx.service
(二)给Nginx欢迎界面做标记,好看出实验效果
[root@server1 ~]# vim /usr/share/nginx/html/index.html
#主机server1 nginx的其他配置server2
四、测试client
(一)访问VIP http://192.168.136.140
(二)拔掉master的网线
(三)访问VIP http://192.168.136.140,观察网页已经切换
五、关于keepalived对nginx状态未知的问题
思考:nginx服务的状态和keepalived的关系?
恢复之前的实验。启动两台主机的keepalived和nginx。确保页面访问正常。
关闭master的nginx服务 。systemctl stop nginx 继续访问VIP,请问页面是否会切换到slave呢?(将会无法访问nginx,原因是keepalived监控的是接口IP状态。无法监控nginx服务状态)
(一)编辑监控脚本
1.server1添加Nginx监控脚本:
[root@server1 ~]# vim /etc/keepalived/ck_ng.sh
[root@server1 ~]# chmod +x /etc/keepalived/ck_ng.sh
#!/bin/bash
#检查nginx进程是否存在
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
#尝试启动一次nginx,停止5秒后再次检测
service nginx start
sleep 5
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
#如果启动没成功,就杀掉keepalive触发主备切换
service keepalived stop
fi
fi
(二)启动监控脚本
1.清除掉配置文件中的注释。
2.重启keepalived即可。
#主机server1 的编辑监控脚本配置给server2
(三)nginx状态测试
[root@server1 ~]# systemctl stop nginx
[root@server1 ~]# systemctl status nginx
我们发现当nginx服务关闭时直接被拉了起来