首先准备两台机器,每个机器都安装有 keepalived 以及 Nginx,nginx 反向代理两个 tomcat 实现负载均衡,所以每个机器上安装docker 以及 tomcat。
1. 配置 Keepalived
1.1 配置 MASTER
第一步:修改 /etc/hosts 文件, 添加:
127.0.0.1 KEEPALIVED_NGINX_MASTER
第二步:将 KEEPALIVED_NGINX_MASTER 配置到 router_id
第三步:注释掉 vrrp_strict
第四步 :配置 vrrp_instance 的 interface
所以将 interface ens33
第五步:配置 vrrp_instance 的 state 为 MASTER
第六步:配置 virtual_ipaddress
192.168.214.99
全部配置如下:
! 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 KEEPALIVED_NGINX_MASTER
vrrp_skip_check_adv_addr
# vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.214.99
}
}
1.2 配置 BACKUP
第一步:修改 /etc/hosts 文件, 添加:
127.0.0.1 KEEPALIVED_NGINX_BACKUP
第二步:将 KEEPALIVED_NGINX_BACKUP 配置到 router_id
第三步:配置 vrrp_instance 的 state 为 BACKUP
第四步:配置 vrrp_instance 的 statepriority 为 50
其他的配置和 MASTER 保持一致
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 KEEPALIVED_NGINX_BACKUP
vrrp_skip_check_adv_addr
# vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 51
priority 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.214.99
}
}
2. 测试 Keepalived
两台机器的 Nginx 访问页面:
通过 Keepalived 虚拟 ip 访问:
宕掉 MASTER :
3. 通过 shell 脚本优化 keepalived+Nginx 高可用集群
实际情况中 keepalived 不容易挂掉,而容易挂掉的是nginx。
此时的问题是如果 nginx 挂了,但是 keepavlied 没挂,这时候依然可以访问机器但是访问不到服务。
3.1 优化步骤
所以通过 keepalived 的 vrrp_script 配置,来调用自定义shell脚本。
#!/bin/bash
echo 'xxxxxx'
count_nginx=`ps -ef|grep -w nginx|grep -v grep|wc -l`
echo $count_nginx
if [ $count_nginx -eq 0 ];then
systemctl start nginx.service
sleep 2
if [ `ps -ef|grep -w nginx|grep -v grep|wc -l` -eq 0 ];then
systemctl stop keepalived.service
fi
fi
这个 shell 脚本的作用是统计 nginx 进程数,假如是 0 个 说明 Nginx 挂掉了,那就启动 nginx,等2秒,再统计,假如还是0,说明nginx启动失败,就把宕掉 keepalived 切换备份机器,假如不是0,说明启动成功,那就继续运行;
第一步:上面 shell 脚本命名 nginx_check.sh 文件,存/shell/目录下;
第二步:配置 keepalived.conf;
vrrp_script chk_http_port {
script "/shell/nginx_check.sh" #脚本地址
interval 2 #检测脚本执行的间隔
weight 2 #比重
}
第三步:重启 keepalived