KeepLived + nginx 高可用

. 环境准备

1. VMware;
2. 4台CentOs7虚拟主机:192.168.122.217, 192.168.122.165
3. 系统服务:LVS, Keepalived
4. Web服务器:nginx


. 软件安装

在2台虚拟机上,我们以如下方式搭建集群:

192.168.122.217 nginx-1+keepalived-1

192.168.122.165 nginx-2+keepalived-2

两台机器安装keeplived和nginx


yum  install -y keepalived nginx

接下来我们要配置keeplive服务

192.168.122.217配置

cat > /etc/keepalived/keepalived.conf <<EOF
! Configuration File for keepalived
global_defs {
   router_id 192.168.122.217
}
vrrp_script chk_nginx {
    script "/etc/keepalived/check_nginx.sh"
    interval 2
    weight -20
}
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 251
    priority 100
    advert_int 1
    mcast_src_ip 192.168.122.217
    nopreempt
    authentication {
        auth_type PASS
        auth_pass 11111111
    }
    track_script {
         chk_nginx
    }
    virtual_ipaddress {
        192.168.122.50
    }
}
EOF

## 192.168.122.217 为节点IP,192.168.122.50 VIP

192.168.122.165配置

cat > /etc/keepalived/keepalived.conf <<EOF
! Configuration File for keepalived
global_defs {
   router_id 192.168.122.165
}
vrrp_script chk_nginx {
    script "/etc/keepalived/check_nginx.sh"
    interval 2
    weight -20
}
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 251
    priority 100
    advert_int 1
    mcast_src_ip 192.168.122.165
    nopreempt
    authentication {
        auth_type PASS
        auth_pass 11111111
    }
    track_script {
         chk_nginx
    }
    virtual_ipaddress {
        192.168.122.50
    }
}
EOF

## 192.168.122.165 为节点IP,192.168.122.50 VIP

创建健康检查脚本,脚本放在/etc/keepalived/check_nginx.sh ,两台机都要放

[root@fefgegrege opt]# cat check_nginx.sh 
        PORT_PROCESS=`ps aux|grep -v grep|grep nginx|wc -l`
        if [ $PORT_PROCESS -eq 0 ];then
                echo "nginx Is Not Used,End."
                exit 1
        fi
        echo "Check nginx Cant Be Empty!"

两台机启动keeplived

[root@gergergrehre]# systemctl enable --now keepalived
Created symlink from /etc/systemd/system/multi-user.target.wants/keepalived.service to /usr/lib/systemd/system/keepalived.service.

启动完毕后ping 192.168.122.50 (VIP)

[root@hdththt ~]# ping 192.168.122.50
PING 192.168.122.50 (192.168.122.50) 56(84) bytes of data.
64 bytes from 192.168.122.50: icmp_seq=1 ttl=64 time=1.37 ms
64 bytes from 192.168.122.50: icmp_seq=2 ttl=64 time=0.515 ms
64 bytes from 192.168.122.50: icmp_seq=3 ttl=64 time=0.594 ms
64 bytes from 192.168.122.50: icmp_seq=4 ttl=64 time=0.831 ms
^C
--- 192.168.122.50 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3001ms
rtt min/avg/max/mdev = 0.515/0.829/1.376/0.336 ms

#如果没有启动,请检查原因。 ps -ef|grep keep 检查是否启动成功
#没有启动成功,请执行下面命令,从新启动。启动成功vip肯定就通了
systemctl start keepalived