keepalive高可用

keepalive高可用

文章目录

    • 1. keepalived简介
      • 1.1 keepalived是什么?
      • 1.2 keepalived的重要功能
      • 1.3 keepalived高可用故障转移的原理
      • 1.4 keepalived原理
        • 1.4.1 keepalived高可用架构图
        • 1.4.2 keepalived工作原理描述
    • 2. keepalived配置文件讲解
      • 2.1 keepalived默认配置文件
      • 2.2 定制主配置文件
      • 2.3 实例
    • keepalived实现nginx负载均衡机高可用
      • 安装keepalived
      • 安装nginx负载均衡机
      • keepalived配置
        • 配置主keepalived
        • 配置备keepalived
        • 测试keepalived的故障转移
      • keepalived加入脚本监控nginx负载均衡机
        • 编写监控脚本
        • keepalived加入监控脚本的配置


1. keepalived简介

1.1 keepalived是什么?

Keepalived 软件起初是专为LVS负载均衡软件设计的,用来管理并监控LVS集群系统中各个服务节点的状态,后来又加入了可以实现高可用的VRRP功能。因此,Keepalived除了能够管理LVS软件外,还可以作为其他服务(例如:Nginx、Haproxy、MySQL等)的高可用解决方案软件。

Keepalived软件主要是通过VRRP协议实现高可用功能的。VRRP是Virtual Router RedundancyProtocol(虚拟路由器冗余协议)的缩写,VRRP出现的目的就是为了解决静态路由单点故障问题的,它能够保证当个别节点宕机时,整个网络可以不间断地运行。

所以,Keepalived 一方面具有配置管理LVS的功能,同时还具有对LVS下面节点进行健康检查的功能,另一方面也可实现系统网络服务的高可用功能。

keepalived官网

1.2 keepalived的重要功能

keepalived 有三个重要的功能,分别是:

  • 管理LVS负载均衡软件
  • 实现LVS集群节点的健康检查
  • 作为系统网络服务的高可用性(failover)

1.3 keepalived高可用故障转移的原理

Keepalived 高可用服务之间的故障切换转移,是通过 VRRP (Virtual Router Redundancy Protocol ,虚拟路由器冗余协议)来实现的。

在 Keepalived 服务正常工作时,主 Master 节点会不断地向备节点发送(多播的方式)心跳消息,用以告诉备 Backup 节点自己还活看,当主 Master 节点发生故障时,就无法发送心跳消息,备节点也就因此无法继续检测到来自主 Master 节点的心跳了,于是调用自身的接管程序,接管主 Master 节点的 IP 资源及服务。而当主 Master 节点恢复时,备 Backup 节点又会释放主节点故障时自身接管的IP资源及服务,恢复到原来的备用角色。

那么,什么是VRRP呢?
VRRP ,全 称 Virtual Router Redundancy Protocol ,中文名为虚拟路由冗余协议 ,VRRP的出现就是为了解决静态踣甶的单点故障问题,VRRP是通过一种竞选机制来将路由的任务交给某台VRRP路由器的。

1.4 keepalived原理

1.4.1 keepalived高可用架构图

keepalive高可用_第1张图片

1.4.2 keepalived工作原理描述

Keepalived高可用对之间是通过VRRP通信的,因此,我们从 VRRP开始了解起:
\1) VRRP,全称 Virtual Router Redundancy Protocol,中文名为虚拟路由冗余协议,VRRP的出现是为了解决静态路由的单点故障。
\2) VRRP是通过一种竟选协议机制来将路由任务交给某台 VRRP路由器的。
\3) VRRP用 IP多播的方式(默认多播地址(224.0_0.18))实现高可用对之间通信。
\4) 工作时主节点发包,备节点接包,当备节点接收不到主节点发的数据包的时候,就启动接管程序接管主节点的开源。备节点可以有多个,通过优先级竞选,但一般 Keepalived系统运维工作中都是一对。
\5) VRRP使用了加密协议加密数据,但Keepalived官方目前还是推荐用明文的方式配置认证类型和密码。

介绍完 VRRP,接下来我再介绍一下 Keepalived服务的工作原理:

Keepalived高可用是通过 VRRP 进行通信的, VRRP是通过竞选机制来确定主备的,主的优先级高于备,因此,工作时主会优先获得所有的资源,备节点处于等待状态,当主挂了的时候,备节点就会接管主节点的资源,然后顶替主节点对外提供服务。

在 Keepalived 服务之间,只有作为主的服务器会一直发送 VRRP 广播包,告诉备它还活着,此时备不会枪占主,当主不可用时,即备监听不到主发送的广播包时,就会启动相关服务接管资源,保证业务的连续性.接管速度最快可以小于1秒。

2. keepalived配置文件讲解

2.1 keepalived默认配置文件

keepalived 的主配置文件是 /etc/keepalived/keepalived.conf。其内容如下:

[root@master ~]# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {       //全局配置
   notification_email {     //定义报警收件人邮件地址
     [email protected]
     [email protected]
     [email protected]
   }
   notification_email_from [email protected]    //定义报警发件人邮箱
   smtp_server 192.168.200.1    //邮箱服务器地址
   smtp_connect_timeout 30      //定义邮箱超时时间
   router_id LVS_DEVEL          //定义路由标识信息,同局域网内唯一
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_instance VI_1 {        //定义实例
    state MASTER            //指定keepalived节点的初始状态,可选值为MASTER|BACKUP
    interface eth0          //VRRP实例绑定的网卡接口,用户发送VRRP包
    virtual_router_id 51    //虚拟路由的ID,同一集群要一致
    priority 100            //定义优先级,按优先级来决定主备角色,优先级越大越优先
    nopreempt               //设置不抢占
    advert_int 1            //主备通讯时间间隔
    authentication {        //配置认证
        auth_type PASS      //认证方式,此处为密码
        auth_pass 1111      //同一集群中的keepalived配置里的此处必须一致,推荐使用8位随机数
    }
    virtual_ipaddress {     //配置要使用的VIP地址
        192.168.200.16
    }
}

virtual_server 192.168.200.16 1358 {    //配置虚拟服务器
    delay_loop 6        //健康检查的时间间隔
    lb_algo rr          //lvs调度算法
    lb_kind NAT         //lvs模式
    persistence_timeout 50      //持久化超时时间,单位是秒
    protocol TCP        //4层协议

    sorry_server 192.168.200.200 1358   //定义备用服务器,当所有RS都故障时用sorry_server来响应客户端

    real_server 192.168.200.2 1358 {    //定义真实处理请求的服务器
        weight 1    //给服务器指定权重,默认为1
        HTTP_GET {
            url {
              path /testurl/test.jsp    //指定要检查的URL路径
              digest 640205b7b0fc66c1ea91c463fac6334d   //摘要信息
            }
            url {
              path /testurl2/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            url {
              path /testurl3/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334d
            }
            connect_timeout 3       //连接超时时间
            nb_get_retry 3          //get尝试次数
            delay_before_retry 3    //在尝试之前延迟多长时间
        }
    }

    real_server 192.168.200.3 1358 {
        weight 1
        HTTP_GET {
            url {
              path /testurl/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334c
            }
            url {
              path /testurl2/test.jsp
              digest 640205b7b0fc66c1ea91c463fac6334c
            }
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}

2.2 定制主配置文件

vrrp_instance段配置

nopreempt   //设置为不抢占。默认是抢占的,当高优先级的机器恢复后,会抢占低优先 \
级的机器成为MASTER,而不抢占,则允许低优先级的机器继续成为MASTER,即使高优先级 \
的机器已经上线。如果要使用这个功能,则初始化状态必须为BACKUP。

preempt_delay   //设置抢占延迟。单位是秒,范围是0---1000,默认是0.发现低优先 \
级的MASTER后多少秒开始抢占。

vrrp_script段配置

//作用:添加一个周期性执行的脚本。脚本的退出状态码会被调用它的所有的VRRP Instance记录。
//注意:至少有一个VRRP实例调用它并且优先级不能为0.优先级范围是1-254.
vrrp_script  {
          ...
    }

//选项说明:
script "/path/to/somewhere"      //指定要执行的脚本的路径。
interval               //指定脚本执行的间隔。单位是秒。默认为1s。
timeout                //指定在多少秒后,脚本被认为执行失败。
weight <-254 --- 254>           //调整优先级。默认为2.
rise                   //执行成功多少次才认为是成功。
fall                   //执行失败多少次才认为失败。
user  [GROUPNAME]     //运行脚本的用户和组。
init_fail                       //假设脚本初始状态是失败状态。

//weight说明: 
1. 如果脚本执行成功(退出状态码为0),weight大于0,则priority增加。
2. 如果脚本执行失败(退出状态码为非0),weight小于0,则priority减少。
3. 其他情况下,priority不变。

real_server段配置

weight             //给服务器指定权重。默认是1
inhibit_on_failure      //当服务器健康检查失败时,将其weight设置为0, \
                        //而不是从Virtual Server中移除
notify_up       //当服务器健康检查成功时,执行的脚本
notify_down     //当服务器健康检查失败时,执行的脚本
uthreshold         //到这台服务器的最大连接数
lthreshold         //到这台服务器的最小连接数

tcp_check段配置

connect_ip      //连接的IP地址。默认是real server的ip地址
connect_port          //连接的端口。默认是real server的端口
bindto          //发起连接的接口的地址。
bind_port             //发起连接的源端口。
connect_timeout        //连接超时时间。默认是5s。
fwmark             //使用fwmark对所有出去的检查数据包进行标记。
warmup     //指定一个随机延迟,最大为N秒。可防止网络阻塞。如果为0,则关闭该功能。
retry                 //重试次数。默认是1次。
delay_before_retry     //默认是1秒。在重试之前延迟多少秒。

2.3 实例

global_defs {
    router_id LVS_Server
}
vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 150
    nopreempt
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass yefeng
    }
    virtual_ipaddress {  
        172.16.12.250
    }
}
virtual_server 172.16.12.250 80 {
    delay_loop 3
    lvs_sched rr
    lvs_method DR
    protocol TCP
    real_server 172.16.12.129 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
    real_server 172.16.12.130 8080 {
        weight 1
        TCP_CHECK {
            connect_port 8080
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}

keepalived实现nginx负载均衡机高可用

环境说明

主机名 IP 应用软件 系统
master 192.168.92.130 keepalived、nginx Centos8
slave 192.168.92.139 keepalived、nginx Centos8

前言

高可用虚拟IP(VIP)设为192.168.92.200。在企业的生产环境中的VIP是公网IP。

另外,此处安装的nginx只是充当负载均衡机做实验,测试keepalived高可用的功能能否实现。虽说nginx有此功能,但本次实验并未涉及配置nginx的负载均衡

安装keepalived

配置主keepalived

#关闭防火墙与SELINUX
[root@master ~]# systemctl stop firewalld
[root@master ~]# systemctl disable firewalld
[root@master ~]# setenforce 0
[root@master ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config

#配置网络源
[root@master ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
[root@master ~]# sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo

#安装keepalived及其它工具
[root@master ~]# dnf -y install epel-release vim wget gcc gcc-c++
[root@master ~]# dnf -y install keepalived

#查看安装keepalived生成的文件
[root@master ~]# rpm -ql keepalived
/etc/keepalived     				#配置目录
/etc/keepalived/keepalived.conf     #主配置文件
/etc/sysconfig/keepalived
/usr/bin/genhash
/usr/lib/systemd/system/keepalived.service      #服务控制文件
/usr/libexec/keepalived
/usr/sbin/keepalived
.....此处省略N行......

配置备keepalived

#关闭防火墙与SELINUX
[root@slave ~]# systemctl stop firewalld
[root@slave ~]# systemctl disable firewalld
[root@slave ~]# setenforce 0
[root@slave ~]# sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config

#配置网络源
[root@slave ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
[root@slave ~]# sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo

#安装keepalived及其它工具
[root@slave ~]# dnf -y install epel-release vim wget gcc gcc-c++
[root@slave ~]# dnf -y install keepalived

安装nginx负载均衡机

在master上安装nginx

#安装nginx
[root@master ~]# yum -y install nginx
#进到nginx的网站内容存放目录
[root@master ~]# cd /usr/share/nginx/html/
[root@master html]# ls
404.html  50x.html  index.html  nginx-logo.png  poweredby.png
#将原有的首页文件备份。建议养此好习惯,这样的话就算错误操作了,也能恢复
[root@master html]# mv index.html{,.bak}
#将首页文件的内容设为master,以便测试高可用
[root@master html]# echo 'master' > index.html
[root@master html]# ls
404.html  50x.html  index.html  index.html.bak  nginx-logo.png  poweredby.png
#将nginx开启并设为开机自启
[root@master html]# systemctl start nginx
[root@master html]# systemctl enable nginx
#查看nginx的默认80端口是否开启
[root@master html]# ss -anlt
State       Recv-Q      Send-Q             Local Address:Port             Peer Address:Port      Process
LISTEN      0           128                      0.0.0.0:80                    0.0.0.0:*
LISTEN      0           128                      0.0.0.0:22                    0.0.0.0:*
LISTEN      0           128                         [::]:80                       [::]:*
LISTEN      0           128                         [::]:22                       [::]:*

在slave上安装nginx

#安装nginx
[root@slave ~]# yum -y install nginx
#进到nginx的网站内容存放目录
[root@slave ~]# cd /usr/share/nginx/html/
[root@slave html]# ls
404.html  50x.html  index.html  nginx-logo.png  poweredby.png
#将原有的首页文件备份
[root@slave html]# mv index.html{,.bak}
#将首页文件的内容设为slave,以便测试高可用
[root@slave html]# echo 'slave' > index.html
[root@slave html]# ls
404.html  50x.html  index.html  index.html.bak  nginx-logo.png  poweredby.png
#先将nginx开启,但不设为开机自启。目前开启是因为要先测试负载均衡是否能使用
#因这台负载均衡器是备用的,在主负载均衡工作时,备用的不可工作。
[root@slave html]# systemctl start nginx
#查看nginx的默认80端口是否开启
[root@slave html]# ss -anlt
State       Recv-Q      Send-Q             Local Address:Port             Peer Address:Port      Process
LISTEN      0           128                      0.0.0.0:80                    0.0.0.0:*
LISTEN      0           128                      0.0.0.0:22                    0.0.0.0:*
LISTEN      0           128                         [::]:80                       [::]:*
LISTEN      0           128                         [::]:22                       [::]:*

做完上述的安装nginx操作后,去浏览器测试访问,确保nginx服务能够正常访问

keepalived配置

配置主keepalived

#生成一串8位数的随机数作为认证密码,该密码主备keepalived要一致。用户无需记住
[root@master ~]# strings /dev/urandom |tr -dc A-Za-z0-9 | head -c8; echo
JfUd6P4H

[root@master ~]# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id lb01
}

vrrp_instance VI_1 {
    state MASTER
    interface ens32
    virtual_router_id 81
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass JfUd6P4H
    }
    virtual_ipaddress {
        192.168.92.200
    }
}

virtual_server 192.168.92.200 80 {
    delay_loop 6
    lb_algo rr
    lb_kind DR
    persistence_timeout 50
    protocol TCP

    real_server 192.168.92.130 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }

    real_server 192.168.92.139 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}

#开启keepalived并设为开机自启
[root@master ~]# systemctl enable --now keepalived.service
#查看有无VIP
[root@master ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e4:f5:9d brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.130/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1507sec preferred_lft 1507sec
    inet 192.168.92.200/32 scope global ens32		#可以看到主keepalived有了VIP
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fee4:f59d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

配置备keepalived

[root@slave ~]# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id lb02
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens32
    virtual_router_id 81
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass JfUd6P4H
    }
    virtual_ipaddress {
        192.168.92.200
    }
}

virtual_server 192.168.92.200 80 {
    delay_loop 6
    lb_algo rr
    lb_kind DR
    persistence_timeout 50
    protocol TCP

    real_server 192.168.92.130 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }

    real_server 192.168.92.139 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}

#开启keepalived并设为开机自启
[root@slave ~]# systemctl enable --now keepalived.service
#查看有无VIP。可以看到备keepalived没有VIP,这是因为VIP只在主keepalived上有
#当master主机挂掉之后,slave主机会成为新的主keepalive,这时自然会有VIP了
[root@slave ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:12:fa:33 brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.139/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1266sec preferred_lft 1266sec
    inet6 fe80::20c:29ff:fe12:fa33/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

测试keepalived的故障转移

192.168.92.200是VIP

#此时master是主keepalived,自然VIP也在
[root@master ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e4:f5:9d brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.130/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1507sec preferred_lft 1507sec
    inet 192.168.92.200/32 scope global ens32
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fee4:f59d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
#手动停止keepalived,模拟该主机发生故障。可以看到VIP消失了
[root@master ~]# systemctl stop keepalived.service
[root@master ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e4:f5:9d brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.130/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1717sec preferred_lft 1717sec
    inet6 fe80::20c:29ff:fee4:f59d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

#这时去查看slave,由于大当家挂掉了,slave主机不到1s完成掌权。可以看到有了VIP
[root@slave ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:12:fa:33 brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.139/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1563sec preferred_lft 1563sec
    inet 192.168.92.200/32 scope global ens32
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe12:fa33/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

#主keepalived在濒危之际起死回生!重新夺回VIP(因优先级高)
[root@master ~]# systemctl start keepalived.service
[root@master ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e4:f5:9d brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.130/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1552sec preferred_lft 1552sec
    inet 192.168.92.200/32 scope global ens32
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fee4:f59d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

#这时slave自然失去了VIP,继续静候待命,时刻盯着master的生命状态,随时接替玉玺(VIP)
[root@slave ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:12:fa:33 brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.139/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1288sec preferred_lft 1288sec
    inet6 fe80::20c:29ff:fe12:fa33/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

keepalived加入脚本监控nginx负载均衡机

keepalived通过脚本来监控nginx负载均衡机的状态

需求:一旦主keepalived挂掉了,那么自动让备keepalived成为新的主keepalived,达到高可用的效果。

编写监控脚本

在master上编写脚本

[root@master ~]# mkdir /scripts
[root@master ~]# cd /scripts/
[root@master scripts]# vim check_nginx.sh
#!/bin/bash
#该脚本用于检查nginx是否在运行,如无nginx的进程则停止keepalived,达到故障转移(主备切换)的效果
nginx_status=$(ps -ef|grep -Ev "grep|$0"|grep '\bnginx\b'|wc -l)
if [ $nginx_status -lt 1 ];then
    systemctl stop keepalived
fi
[root@master scripts]# chmod +x check_nginx.sh

[root@master scripts]# vim notify.sh
#!/bin/bash
case "$1" in
  master)
        nginx_status=$(ps -ef|grep -Ev "grep|$0"|grep '\bnginx\b'|wc -l)
        if [ $nginx_status -lt 1 ];then
            systemctl start nginx
        fi
  ;;
  backup)
        nginx_status=$(ps -ef|grep -Ev "grep|$0"|grep '\bnginx\b'|wc -l)
        if [ $nginx_status -gt 0 ];then
            systemctl stop nginx
        fi
  ;;
  *)
        echo "Usage:$0 master|backup VIP"
  ;;
esac
[root@master scripts]# chmod +x notify.sh
[root@master scripts]# ll
total 8
-rwxr-xr-x 1 root root 267 Oct  8 20:40 check_nginx.sh
-rwxr-xr-x 1 root root 661 Oct  8 20:46 notify.sh

在slave上编写脚本

[root@slave ~]# mkdir /scripts
[root@slave ~]# cd /scripts/
[root@slave scripts]# vim notify.sh
[root@slave scripts]# chmod +x notify.sh
#!/bin/bash
case "$1" in
  master)
        nginx_status=$(ps -ef|grep -Ev "grep|$0"|grep '\bnginx\b'|wc -l)
        if [ $nginx_status -lt 1 ];then
            systemctl start nginx
        fi
  ;;
  backup)
        nginx_status=$(ps -ef|grep -Ev "grep|$0"|grep '\bnginx\b'|wc -l)
        if [ $nginx_status -gt 0 ];then
            systemctl stop nginx
        fi
  ;;
  *)
        echo "Usage:$0 master|backup VIP"
  ;;
esac

测试监控脚本是否可用

[root@master scripts]# ./notify.sh backup
[root@master scripts]# systemctl status nginx.service
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Sat 2022-10-08 21:20:56 CST; 1min 1s ago
[root@master scripts]# ./check_nginx.sh
[root@master scripts]# systemctl status keepalived.service
● keepalived.service - LVS and VRRP High Availability Monitor
   Loaded: loaded (/usr/lib/systemd/system/keepalived.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Sat 2022-10-08 21:12:57 CST; 25s ago
#当nginx服务停止后,keepalived也相继停止。此时salve成为新的主keepalived,VIP也跟随过去了。
[root@master scripts]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e4:f5:9d brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.130/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1254sec preferred_lft 1254sec
    inet6 fe80::20c:29ff:fee4:f59d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
#当nginx与keepalived运行后,由于master配置的优先级高,再次成为主keepalived,VIP也回来了。
[root@master scripts]# systemctl start keepalived.service
[root@master scripts]# ./notify.sh master
[root@master scripts]# systemctl status nginx.service
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Sat 2022-10-08 21:14:30 CST; 13s ago
[root@master scripts]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e4:f5:9d brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.130/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1110sec preferred_lft 1110sec
    inet 192.168.92.200/32 scope global ens32
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fee4:f59d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

keepalived加入监控脚本的配置

配置主keepalived

[root@master ~]# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id lb01
}

vrrp_script nginx_check {				#在原有的配置中加入vrrp_script这段
    script "/scripts/check_nginx.sh"	#填入要执行的脚本的路径
    interval 1
    weight -20
}

vrrp_instance VI_1 {
    state MASTER
    interface ens32
    virtual_router_id 81
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass JfUd6P4H
    }
    virtual_ipaddress {
        192.168.92.200
    }
    track_script {		#在原有的配置中加入track_script这段
        nginx_check
    }
    notify_master "/scripts/notify.sh master"	#在原有的配置中加入此条
}

virtual_server 192.168.92.200 80 {
    delay_loop 6
    lb_algo rr
    lb_kind DR
    persistence_timeout 50
    protocol TCP

    real_server 192.168.92.130 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }

    real_server 192.168.92.139 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}
#重启服务,生效配置
[root@master ~]# systemctl restart keepalived.service

配置备keepalived

salve无需检测nginx是否正常,当升级为MASTER时启动nginx,当降级为BACKUP时关闭nginx。

[root@slave ~]# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
   router_id lb02
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens32
    virtual_router_id 81
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass JfUd6P4H
    }
    virtual_ipaddress {
        192.168.92.200
    }
    notify_master "/scripts/notify.sh master"	#在原有的配置中加入此条
    notify_backup "/scripts/notify.sh backup"	#在原有的配置中加入此条
}

virtual_server 192.168.92.200 80 {
    delay_loop 6
    lb_algo rr
    lb_kind DR
    persistence_timeout 50
    protocol TCP

    real_server 192.168.92.130 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }

    real_server 192.168.92.139 80 {
        weight 1
        TCP_CHECK {
            connect_port 80
            connect_timeout 3
            nb_get_retry 3
            delay_before_retry 3
        }
    }
}
[root@slave ~]# systemctl restart keepalived.service

测试加入配置中的监控脚本能否随着nginx服务的状态而切换主备

#模拟nginx服务故障
[root@master ~]# systemctl stop nginx
#可以看到由于keepalived监听到nginx服务故障了,随后停止了keepalived,达到了自动切换主备进行故障转移的效果
[root@master ~]# systemctl status keepalived.service
● keepalived.service - LVS and VRRP High Availability Monitor
   Loaded: loaded (/usr/lib/systemd/system/keepalived.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Sat 2022-10-08 21:58:40 CST; 1min 9s ago
#理所当然的VIP也没有了
[root@master ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e4:f5:9d brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.130/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1195sec preferred_lft 1195sec
    inet6 fe80::20c:29ff:fee4:f59d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
#从slave端可以看到此时VIP在这里,也就是说监听到主keepalived挂掉了进而取而代之了
[root@slave ~]# 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: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:12:fa:33 brd ff:ff:ff:ff:ff:ff
    inet 192.168.92.139/24 brd 192.168.92.255 scope global dynamic noprefixroute ens32
       valid_lft 1103sec preferred_lft 1103sec
    inet 192.168.92.200/32 scope global ens32
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe12:fa33/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

你可能感兴趣的:(服务管理,keepalived,集群,高可用,Linux,负载均衡)