部署规划
master 192.168.25.128 keepalived01 nginx02
backup 192.168.25.130 keepalived02 nginx02
vip 192.168.25.131
部署实施
master 192.168.25.128
安装nginx 监听80端口
安装keepalived
#keepalived 配置文件
#keepalived配置
cat /etc/keepalived/keepalived.conf
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.17.129
smtp_connect_timeout 30
router_id LVS_DEVEL # 访问到主机,本机的hostname,需要修改
}
vrrp_script chk_http_port {
script “/etc/keepalived/nginx_check.sh” # 检测脚本位置
interval 2 #(检测脚本执行的间隔)
weight 2 # 权重
}
vrrp_instance VI_1 {
state MASTER # 备份服务器上将 MASTER 改为 BACKUP,需要修改
interface ens33 //网卡名字,使用ifconfig查看,需要修改
virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
priority 100 # 主、备机取不同的优先级,主机值较大,备份机值较小,一般主100从90
advert_int 1 # 每隔1秒发送心跳
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.25.131 #// VRRP H 虚拟地址,也可以绑定多个虚拟ip
}
unicast_src_ip 192.168.25.128 #本机ip
unicast_peer {
192.168.25.130 #对端ip
}
}
#健康检查脚本
# cat /etc/keepalived/nginx_check.sh
#!/bin/bash
A=ps -C nginx – no-header |wc -l
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx -p /usr/local/nginx -c conf/nginx.conf
sleep 2
if [ ps -C nginx --no-header |wc -l
-eq 0 ];then
killall keepalived
fi
fi
chmod +x /etc/keepalived/nginx_check.sh
systemctl start keepalived #启动
tail -f /var/log/messages #查看日志
backup 192.168.25.130
#keepalived 配置文件
cat /etc/keepalived/keepalived.conf
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.17.129
smtp_connect_timeout 30
router_id LVS_DEVEL # 访问到主机,本机的hostname,需要修改
}
vrrp_script chk_http_port {
script “/etc/keepalived/nginx_check.sh” # 检测脚本位置
interval 2 #(检测脚本执行的间隔)
weight 2 # 权重
}
vrrp_instance VI_1 {
state BACKUP # 备份服务器上将 MASTER 改为 BACKUP,需要修改
interface ens33 //网卡名字,使用ifconfig查看,需要修改
virtual_router_id 51 # 主、备机的 virtual_router_id 必须相同
priority 90 # 主、备机取不同的优先级,主机值较大,备份机值较小,一般主100从90
advert_int 1 # 每隔1秒发送心跳
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.25.131 #// VRRP H 虚拟地址,也可以绑定多个虚拟ip
}
unicast_src_ip 192.168.25.130 #本机ip
unicast_peer {
192.168.25.128 #对端ip
}
}
#健康检查脚本
cat /etc/keepalived/nginx_check.sh
#!/bin/bash
A=ps -C nginx – no-header |wc -l
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx -p /usr/local/nginx -c conf/nginx.conf #nginx启动路径
sleep 2
if [ ps -C nginx --no-header |wc -l
-eq 0 ];then
killall keepalived
fi
fi
chmod +x /etc/keepalived/nginx_check.sh
systemctl start keepalived #启动
tail -f /var/log/messages #查看日志
方案验证
master上先启动
可以看到此时vip在master上
启动backup
此时只能看到网卡IP
停掉master,测试VIP自动切换
观察backup节点日志
可以看到这里vip已经切换到备节点
外部访问
添加iptables策略放通
外部访问
sudo iptables -I IN_public_allow -p tcp -j ACCEPT
sudo iptables -I IN_public_allow -p udp -j ACCEPT
访问出流量
sudo iptables -A OUTPUT -p tcp -j ACCEPT
sudo iptables -A OUTPUT -p udp -j ACCEPT
转发流量
反向代理测试
关闭原来的master 可以看到已经切换到backup上