others linux服务器运维 django3 监控 k8s golang 数据库 大数据 前端 devops 理论基础 java oracle 运维日志

nginx keepalived实现nginx高可用

访问量:1116 创建时间:2020-10-26
ip 服务 系统版本
192.168.0.21 nginx、keeplaived centos7
192.168.0.22 nginx 、keepalived centos7
192.168.0.25 vip地址 centos7

注意:关闭防火墙并禁用

systemctl stop firewalld
systemctl disable firewalld

软件安装

192.168.0.21\192.168.0.22机器都安装

wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum -y install nginx  keepalived

备机配置192.168.0.21

[root@e1 ~]#cat /etc/keepalived/keepalived.conf
vrrp_script health_check {
   script "/etc/keepalived/check_nginx.sh"
   interval 3
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens192
    virtual_router_id 51
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.0.25
    }
    track_script {
        health_check
    }
}   

备机配置192.168.0.22

[root@e2 ~]# cat /etc/keepalived/keepalived.conf
vrrp_script health_check {
   script "/etc/keepalived/check_nginx.sh" 
   interval 2
}

vrrp_instance VI_1 {
    state MASTER
    interface ens192
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.0.25
    }
    track_script {
        health_check
    }
}

health_check脚本

2个机器都设置

[root@e2 ~]# cat /etc/keepalived/check_nginx.sh
#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
    /usr/sbin/nginx
    sleep 2
    counter=$(ps -C nginx --no-heading|wc -l)
    if [ "${counter}" = "0" ]; then
        /bin/systemctl stop keepalived.service
        #/etc/init.d/keepalived stop
    fi
fi

启动验证

#启动nginx
nginx
#启动keepalived
systemctl start  keepalived.service
[root@e2 ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:50:56:82:51:ce brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.22/23 brd 192.168.1.255 scope global noprefixroute ens192
       valid_lft forever preferred_lft forever
    inet **192.168.0.25**/32 scope global ens192
       valid_lft forever preferred_lft forever
    inet6 fe80::121a:366d:13bb:c531/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
登陆评论: 使用GITHUB登陆