Keepalived介绍、架构和安装

Keepalived介绍、架构和安装

文章目录

  • Keepalived介绍、架构和安装
  • 1.Keepalived(高可用性服务)
    • 1.1 Keepalived介绍
    • 1.2 Keepalived 架构
    • 1.3 Keepalived 相关文件
  • 2.Keepalived安装
    • 2.1 主机初始化
      • 2.1.1 设置网卡名和ip地址
      • 2.1.2 配置镜像源
      • 2.1.3 关闭防火墙
      • 2.1.4 禁用SELinux
      • 2.1.5 设置时区
    • 2.2 包安装
      • 2.2.1 Rocky和CentOS 安装 keepalived
      • 2.2.2 Ubuntu 安装 keepalived
    • 2.3 编译安装
    • 2.4 一键编译安装keepalived脚本

1.Keepalived(高可用性服务)

t1-1

1.1 Keepalived介绍

Keepalived 是一个开源的软件,它提供了用于实现高可用性的解决方案。Keepalived 可以在 Linux 系统上运行,并用于确保关键服务的连续性和可靠性。其主要功能是在多台服务器之间提供故障转移和负载均衡。

以下是 Keepalived 的一些关键特点和功能:

  1. 高可用性:Keepalived 可以确保关键服务的高可用性。通过配置多台服务器,Keepalived 可以监视这些服务器上的服务,当主服务器出现故障时,自动将服务切换到备用服务器,以确保服务的连续性。
  2. 健康检查:Keepalived 可以定期检查服务器上的服务和节点的运行状态。它可以执行各种健康检查,如 TCP 连接、HTTP GET 请求、SMTP 检查等,以确保服务器和服务的正常运行。
  3. 负载均衡:Keepalived 支持负载均衡功能,可以将客户端请求分发到多个服务器上,从而提高系统的性能和可扩展性。
  4. 虚拟 IP 地址(VIP)管理:Keepalived 可以管理虚拟 IP 地址,使多台服务器共享同一个虚拟 IP 地址。这样可以确保即使在主服务器故障时,虚拟 IP 地址仍然可用于服务访问。
  5. 配置灵活:Keepalived 提供了丰富的配置选项,允许管理员根据特定的需求和环境对故障转移和负载均衡进行定制。管理员可以配置监控参数、故障转移策略、权重设置等。

总之,Keepalived 是一个功能强大的工具,可用于确保关键服务的高可用性和负载均衡。通过使用 Keepalived,用户可以建立一个可靠的系统架构,确保即使在服务器故障时,关键服务仍能够继续提供。

官网:http://keepalived.org/

官方文档:https://keepalived.org/documentation.html

1.2 Keepalived 架构

t1-2

图1-2 Keepalived结构图

Keepalived 是一个用于实现高可用性的解决方案,它通常用于确保关键服务的连续性和可靠性。下面是 Keepalived 的架构详解:

  1. VRRP(虚拟路由冗余协议)
    Keepalived 使用 VRRP 协议来实现故障转移和负载均衡。VRRP 允许多个服务器共享一个虚拟 IP 地址(VIP),其中一个服务器被选举为主服务器(Master),其他服务器则作为备用服务器(Backup)。主服务器负责处理传入的流量,而备用服务器则处于待命状态。如果主服务器发生故障,备用服务器将接管虚拟 IP 地址,从而确保服务的连续性。
  2. 健康检查
    Keepalived 可以通过健康检查确保服务器和服务的正常运行。它可以定期检查服务器上的服务和节点的状态,并根据检查结果来决定是否进行故障转移。这些健康检查可以包括 TCP 连接、HTTP GET 请求、SMTP 检查等。
  3. 配置文件
    Keepalived 的配置文件定义了整个系统的行为。配置文件包括定义虚拟 IP 地址、设置监控参数、配置故障转移策略、指定权重和优先级等。管理员可以根据特定的需求和环境对配置文件进行定制。
  4. 状态同步
    Keepalived 主服务器和备用服务器之间通过状态同步机制来保持一致性。这样可以确保备用服务器了解主服务器的状态,并能够在需要时快速接管服务。
  5. 负载均衡
    除了故障转移功能,Keepalived 还支持负载均衡。它可以将客户端请求分发到多个服务器上,以提高系统的性能和可扩展性。
  6. 日志和警报
    Keepalived 通常提供了丰富的日志和警报功能,以便管理员能够及时了解系统状态和事件。这有助于及时发现问题并进行相应的处理。

总之,Keepalived 架构包括 VRRP 协议、健康检查、配置文件、状态同步、负载均衡和日志警报等组件,这些组件共同工作以确保关键服务的高可用性和连续性。通过使用 Keepalived,用户可以建立一个可靠的系统架构,确保即使在服务器故障时,关键服务仍能够继续提供。

  • 用户空间核心组件:
    • vrrp stack:VIP消息通告
    • checkers:监测real server
    • system call:实现 vrrp 协议状态转换时调用脚本的功能
    • SMTP:邮件组件
    • IPVS wrapper:生成IPVS规则
    • Netlink Reflector:网络接口
    • WatchDog:监控进程
  • 控制组件:提供keepalived.conf 的解析器,完成Keepalived配置
  • IO复用器:针对网络目的而优化的自己的线程抽象
  • 内存管理组件:为某些通用的内存管理功能(例如分配,重新分配,发布等)提供访问权限

Keepalived 进程树

# keepalived2.0版以后
/usr/sbin/keepalived -D
\_ /usr/sbin/keepalived -D

# keepalived2.0版以前
Keepalived <-- Parent process monitoring children
\_ Keepalived <-- VRRP child
\_ Keepalived <-- Healthchecking child

1.3 Keepalived 相关文件

  • 软件包名:keepalived
  • 主程序文件:/usr/sbin/keepalived
  • 主配置文件:/etc/keepalived/keepalived.conf
  • 配置文件示例:/usr/share/doc/keepalived/
  • Unit File:/lib/systemd/system/keepalived.service
  • Unit File的环境配置文件:
    • /etc/sysconfig/keepalived CentOS
    • /etc/default/keepalived Ubuntu

注意:CentOS 7 上有 bug,可能有下面情况出现

systemctl restart keepalived #新配置可能无法生效
systemctl stop keepalived;systemctl start keepalived #无法停止进程,需要 kill停止

2.Keepalived安装

2.1 主机初始化

Keepalived 环境准备:

  • 各节点时间必须同步:ntp, chrony
  • 关闭防火墙及SELinux
  • 各节点之间可通过主机名互相通信:非必须
  • 建议使用/etc/hosts文件实现:非必须
  • 各节点之间的root用户可以基于密钥认证的ssh服务完成互相通信:非必须

2.1.1 设置网卡名和ip地址

Rocky 9和CentOS Stream 9:

# Rocky 9和CentOS Stream 9默认支持修改网卡名。
[root@rocky9 ~]# grep 'plugins' /etc/NetworkManager/NetworkManager.conf 
#plugins=keyfile,ifcfg-rh
# 因为网卡命名方式默认是keyfile,默认不支持修改网卡名,既然官方已经默认是keyfile那这里就不去更改网卡名了。

[root@rocky9 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`

[root@rocky9 ~]# nmcli con delete ${ETHNAME} && nmcli connection add type ethernet con-name ${ETHNAME} ifname ${ETHNAME} ipv4.method manual ipv4.address "172.31.0.9/21" ipv4.gateway "172.31.0.2" ipv4.dns "223.5.5.5,180.76.76.76" autoconnect yes && nmcli con reload && nmcli con up ${ETHNAME}
# 172.31.0.9/21中172.31.0.9是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

[root@rocky9 ~]# ip addr
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: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:37:62:95 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 172.31.0.9/21 brd 172.31.7.255 scope global noprefixroute ens160
       valid_lft forever preferred_lft forever
    inet6 fe80::51ca:fd5d:3552:677d/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
# 可以看到ip地址已修改。

Rocky 8、CentOS Stream 8和CentOS 7:

# Rocky 8、CentOS Stream 8和CentOS 7支持修改网卡名。
[root@rocky8 ~]# grep 'plugins' /etc/NetworkManager/NetworkManager.conf 
#plugins=ifcfg-rh
# 因为网卡命名方式默认是ifcfg-rh,支持修改网卡名。

# 修改网卡名称配置文件
[root@rocky8 ~]# sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@ net.ifnames=0 biosdevname=0"@' /etc/default/grub
[root@rocky8 ~]# grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file ...
done

# 修改网卡文件名
[root@rocky8 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`
[root@rocky8 ~]# mv /etc/sysconfig/network-scripts/ifcfg-${ETHNAME} /etc/sysconfig/network-scripts/ifcfg-eth0

[root@rocky8 ~]# shutdown -r now


[root@rocky8 ~]# nmcli dev
DEVICE  TYPE      STATE      CONNECTION         
eth0    ethernet  connected  Wired connection 1 
lo      loopback  unmanaged  --
# 可以看到CONNECTION的名字是Wired connection 1,要改名才可以下面设置。

[root@rocky8 ~]# ETHNAME=`ip addr | awk -F"[ :]" '/^2/{print $3}'`

[root@rocky8 ~]# nmcli connection modify "Wired connection 1" con-name ${ETHNAME}
[root@rocky8 ~]# nmcli dev
DEVICE  TYPE      STATE      CONNECTION 
eth0    ethernet  connected  eth0       
lo      loopback  unmanaged  --  

# 修改ip地址
[root@rocky8 ~]# nmcli con delete ${ETHNAME} && nmcli connection add type ethernet con-name ${ETHNAME} ifname ${ETHNAME} ipv4.method manual ipv4.address "172.31.0.8/21" ipv4.gateway "172.31.0.2" ipv4.dns "223.5.5.5,180.76.76.76" autoconnect yes && nmcli con reload && nmcli dev up eth0
# 172.31.0.8/21中172.31.0.8是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

[root@rocky8 ~]# ip addr
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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:6f:65:d3 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    altname ens160
    inet 172.31.0.8/21 brd 172.31.7.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::e9c9:aa93:4a58:2cc2/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。

Ubuntu:

# Ubuntu先启用root用户,并设置密码
raymond@ubuntu2204:~$ cat set_root_login.sh 
#!/bin/bash

read -p "请输入密码: " PASSWORD
echo ${PASSWORD} |sudo -S sed -ri 's@#(PermitRootLogin )prohibit-password@\1yes@' /etc/ssh/sshd_config
sudo systemctl restart sshd
sudo -S passwd root <<-EOF
${PASSWORD}
${PASSWORD}
EOF

raymond@ubuntu2204:~$ bash set_root_login.sh 
请输入密码: 123456
[sudo] password for raymond: New password: Retype new password: passwd: password updated successfully

raymond@ubuntu2204:~$ rm -rf set_root_login.sh

# 使用root登陆,修改网卡名
root@ubuntu2204:~# sed -ri.bak '/^GRUB_CMDLINE_LINUX=/s@"$@net.ifnames=0 biosdevname=0"@' /etc/default/grub
root@ubuntu2204:~# grub-mkconfig -o /boot/grub/grub.cfg
Sourcing file `/etc/default/grub'
Sourcing file `/etc/default/grub.d/init-select.cfg'
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-5.15.0-88-generic
Found initrd image: /boot/initrd.img-5.15.0-88-generic
Warning: os-prober will not be executed to detect other bootable partitions.
Systems on them will not be added to the GRUB boot configuration.
Check GRUB_DISABLE_OS_PROBER documentation entry.
done

# Ubuntu 20.04设置ip地址
root@ubuntu2004:~# cat > /etc/netplan/00-installer-config.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.20/21] 
      gateway4: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu20.04网卡配置文件是00-installer-config.yaml;172.31.0.20/21中172.31.0.20是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

# Ubuntu 18.04设置ip地址
root@ubuntu1804:~# cat > /etc/netplan/01-netcfg.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.18/21] 
      gateway4: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu18.04网卡配置文件是01-netcfg.yaml;172.31.0.18/21中172.31.0.18是ip地址,21是子网位数;172.31.0.2是网关地址;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

root@ubuntu2004:~# shutdown -r now

root@ubuntu2004:~# ip addr
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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:e5:98:6f brd ff:ff:ff:ff:ff:ff
    inet 172.31.0.20/21 brd 172.31.7.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fee5:986f/64 scope link 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。

# Ubuntu 22.04设置ip地址
root@ubuntu2204:~# cat > /etc/netplan/00-installer-config.yaml <<-EOF
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: no
      dhcp6: no
      addresses: [172.31.0.22/21]
      routes:
        - to: default
          via: 172.31.0.2
      nameservers:
        addresses: [223.5.5.5, 180.76.76.76]
EOF
# 说明:Ubuntu 22.04网卡配置文件是00-installer-config.yaml;172.31.0.22/21中172.31.0.22是ip地址,21是子网位数;172.31.0.2是网关地址,Ubuntu 22.04设置网关地址的方法发生了改变,参考上面的方法;223.5.5.5, 180.76.76.76都是DNS,根据自己的需求修改。

root@ubuntu2204:~# shutdown -r now

# 重启后使用新设置的ip登陆
root@ubuntu2204:~# ip addr
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: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:a7:be:f2 brd ff:ff:ff:ff:ff:ff
    altname enp2s1
    altname ens33
    inet 172.31.0.22/21 brd 172.31.7.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fea7:bef2/64 scope link 
       valid_lft forever preferred_lft forever
# 重启系统后可以看到网卡名已经修改成eth0,ip地址也已修改。

2.1.2 配置镜像源

Rocky 8和9:

MIRROR=mirrors.sjtug.sjtu.edu.cn
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://'${MIRROR}'/rocky|g' /etc/yum.repos.d/[Rr]ocky*.repo

dnf clean all && dnf makecache

CentOS Stream 9:

cat update_mirror.pl
#!/usr/bin/perl

use strict;
use warnings;
use autodie;

# 要修改镜像源,请去修改url变量!
my $url = 'mirrors.aliyun.com';
my $mirrors = "https://$url/centos-stream";

if (@ARGV < 1) {
    die "Usage: $0 <filename1> <filename2> ...\n";
}

while (my $filename = shift @ARGV) {
    my $backup_filename = $filename . '.bak';
    rename $filename, $backup_filename;

    open my $input, "<", $backup_filename;
    open my $output, ">", $filename;

    while (<$input>) {
        s/^metalink/# metalink/;

        if (m/^name/) {
            my (undef, $repo, $arch) = split /-/;
            $repo =~ s/^\s+|\s+$//g;
            ($arch = defined $arch ? lc($arch) : '') =~ s/^\s+|\s+$//g;

            if ($repo =~ /^Extras/) {
                $_ .= "baseurl=${mirrors}/SIGs/\$releasever-stream/extras" . ($arch eq 'source' ? "/${arch}/" : "/\$basearch/") . "extras-common\n";
            } else {
                $_ .= "baseurl=${mirrors}/\$releasever-stream/$repo" . ($arch eq 'source' ? "/" : "/\$basearch/") . ($arch ne '' ? "${arch}/tree/" : "os") . "\n";
            }
        }

        print $output $_;
    }
}

rpm -q perl &> /dev/null || { echo -e "\\033[01;31m "安装perl工具,请稍等..."\033[0m";yum -y install perl ; }

perl ./update_mirror.pl /etc/yum.repos.d/centos*.repo

dnf clean all && dnf makecache

CentOS Stream 8:

MIRROR=mirrors.aliyun.com
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org/$contentdir|baseurl=https://'${MIRROR}'/centos|g' /etc/yum.repos.d/CentOS-*.repo

dnf clean all && dnf makecache

CentOS 7:

MIRROR=mirrors.aliyun.com
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org|baseurl=https://'${MIRROR}'|g' /etc/yum.repos.d/CentOS-*.repo

yum clean all && yum makecache

Ubuntu 22.04和20.04:

MIRROR=mirrors.aliyun.com
OLD_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu/? $(lsb_release -cs) main.*@\2@p" /etc/apt/sources.list`

sed -i.bak 's/'${OLD_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list

apt update

Ubuntu 18.04:

MIRROR=mirrors.aliyun.com
OLD_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu/? $(lsb_release -cs) main.*@\2@p" /etc/apt/sources.list`

sed -i.bak 's/'${OLD_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list

SECURITY_MIRROR=`sed -rn "s@^deb http(.*)://(.*)/ubuntu $(lsb_release -cs)-security main.*@\2@p" /etc/apt/sources.list`

sed -i.bak 's/'${SECURITY_MIRROR}'/'${MIRROR}'/g' /etc/apt/sources.list

apt update

2.1.3 关闭防火墙

# Rocky和CentOS
systemctl disable --now firewalld

# CentOS 7
systemctl disable --now NetworkManager

# Ubuntu
systemctl disable --now ufw

2.1.4 禁用SELinux

#CentOS
setenforce 0
sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config

#Ubuntu
Ubuntu没有安装SELinux,不用设置

2.1.5 设置时区

ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
echo 'Asia/Shanghai' >/etc/timezone

#Ubuntu还要设置下面内容
cat >> /etc/default/locale <<-EOF
LC_TIME=en_DK.UTF-8
EOF

2.2 包安装

2.2.1 Rocky和CentOS 安装 keepalived

[root@rocky9 ~]# dnf -y install keepalived

[root@rocky9 ~]# dnf info keepalived
Last metadata expiration check: 0:08:41 ago on Fri 19 Jan 2024 06:43:47 PM CST.
Installed Packages
Name         : keepalived
Version      : 2.2.8
Release      : 3.el9
Architecture : x86_64
Size         : 1.6 M
Source       : keepalived-2.2.8-3.el9.src.rpm
Repository   : @System
From repo    : appstream
Summary      : High Availability monitor built upon LVS, VRRP and service pollers
URL          : http://www.keepalived.org/
License      : GPLv2+
Description  : Keepalived provides simple and robust facilities for load balancing
             : and high availability to Linux system and Linux based infrastructures.
             : The load balancing framework relies on well-known and widely used
             : Linux Virtual Server (IPVS) kernel module providing Layer4 load
             : balancing. Keepalived implements a set of checkers to dynamically and
             : adaptively maintain and manage load-balanced server pool according
             : their health. High availability is achieved by VRRP protocol. VRRP is
             : a fundamental brick for router failover. In addition, keepalived
             : implements a set of hooks to the VRRP finite state machine providing
             : low-level and high-speed protocol interactions. Keepalived frameworks
             : can be used independently or all together to provide resilient
             : infrastructures.

[root@rocky9 ~]# systemctl start keepalived
Job for keepalived.service failed because the control process exited with error code.
See "systemctl status keepalived.service" and "journalctl -xeu keepalived.service" for details.
# 启动不了服务

[root@rocky9 ~]# tail -f /var/log/messages
...
Jan 19 20:20:08 rocky9 Keepalived_vrrp[12089]: (/etc/keepalived/keepalived.conf: Line 21) WARNING - interface eth0 for vrrp_instance VI_1 doesn't exist
# 日志里看到“/etc/keepalived/keepalived.conf”文件的第21行vrrp_instance VI_1 的接口 eth0 不存在。

[root@rocky9 ~]# ip addr
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: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:37:62:95 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 172.31.0.9/21 brd 172.31.7.255 scope global noprefixroute ens160
       valid_lft forever preferred_lft forever
    inet6 fe80::6815:42a:c9fb:da05/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
# 可以看到本机的网卡名是ens160

[root@rocky9 ~]# vim /etc/keepalived/keepalived.conf
...
vrrp_instance VI_1 {
    state MASTER
# 把下面内容
    interface eth0
# 修改为
    interface ens160

[root@rocky9 ~]# systemctl start keepalived
# 现在就可以正常启动服务了

[root@rocky9 ~]# ps auxf |grep keepalived
root       12103  0.0  0.1   6408  2180 pts/1    S+   20:22   0:00              \_ grep --color=auto keepalived
root       12096  0.0  0.4  24880  8204 ?        Ss   20:22   0:00 /usr/sbin/keepalived --dont-fork -D
root       12097  0.0  0.3  25228  5848 ?        S    20:22   0:00  \_ /usr/sbin/keepalived --dont-fork -D
root       12098  0.0  0.2  24952  3756 ?        S    20:22   0:00  \_ /usr/sbin/keepalived --dont-fork -D

[root@rocky9 ~]# pstree -p
...
           ├─keepalived(13223)─┬─keepalived(13224)
           │                   └─keepalived(13225)
...

2.2.2 Ubuntu 安装 keepalived

root@ubuntu2204:~# apt -y install keepalived

root@ubuntu2204:~# dpkg -s keepalived
Package: keepalived
Status: install ok installed
Priority: optional
Section: admin
Installed-Size: 1284
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Architecture: amd64
Version: 1:2.2.4-0.2build1
Depends: iproute2, libc6 (>= 2.34), libglib2.0-0 (>= 2.26.0), libmnl0 (>= 1.0.3-4~), libnftnl11 (>= 1.1.2), libnl-3-200 (>= 3.2.27), libnl-genl-3-200 (>= 3.2.7), libpcre2-8-0 (>= 10.22), libsnmp40 (>= 5.9.1+dfsg), libssl3 (>= 3.0.0~~alpha1), libsystemd0
Pre-Depends: init-system-helpers (>= 1.54~)
Recommends: ipvsadm
Conffiles:
 /etc/dbus-1/system.d/org.keepalived.Vrrp1.conf eb86d4c61a0c69d1f98bcf8dcbbd8f60
 /etc/default/keepalived 6b2e3432e4ae31b444058ba2b0d1f06a
 /etc/init.d/keepalived 0312972e0718331b4c90b3b98e623624
Description: Failover and monitoring daemon for LVS clusters
 keepalived is used for monitoring real servers within a Linux
 Virtual Server (LVS) cluster.  keepalived can be configured to
 remove real servers from the cluster pool if it stops responding,
 as well as send a notification email to make the admin aware of
 the service failure.
 .
 In addition, keepalived implements an independent Virtual Router
 Redundancy Protocol (VRRPv2; see rfc2338 for additional info)
 framework for director failover.
 .
 You need a kernel >= 2.4.28 or >= 2.6.11 for keepalived.
 See README.Debian for more information.
Homepage: http://keepalived.org
Original-Maintainer: Alexander Wirt <formorer@debian.org>

root@ubuntu2204:~# dpkg -L keepalived
/.
/etc
/etc/dbus-1
/etc/dbus-1/system.d
/etc/dbus-1/system.d/org.keepalived.Vrrp1.conf
/etc/default
/etc/default/keepalived
/etc/init.d
/etc/init.d/keepalived
/etc/keepalived
/lib
/lib/systemd
/lib/systemd/system
/lib/systemd/system/keepalived.service
/usr
/usr/bin
/usr/sbin
/usr/sbin/keepalived
/usr/share
/usr/share/dbus-1
/usr/share/dbus-1/interfaces
/usr/share/dbus-1/interfaces/org.keepalived.Vrrp1.Instance.xml
/usr/share/dbus-1/interfaces/org.keepalived.Vrrp1.Vrrp.xml
/usr/share/doc
/usr/share/doc/keepalived
/usr/share/doc/keepalived/AUTHOR
/usr/share/doc/keepalived/CONTRIBUTORS
/usr/share/doc/keepalived/README
/usr/share/doc/keepalived/TODO.gz
/usr/share/doc/keepalived/changelog.Debian.gz
/usr/share/doc/keepalived/copyright
/usr/share/doc/keepalived/keepalived.conf.SYNOPSIS
/usr/share/doc/keepalived/samples
/usr/share/doc/keepalived/samples/keepalived.conf.HTTP_GET.port
/usr/share/doc/keepalived/samples/keepalived.conf.IPv6
/usr/share/doc/keepalived/samples/keepalived.conf.PING_CHECK
/usr/share/doc/keepalived/samples/keepalived.conf.SMTP_CHECK
/usr/share/doc/keepalived/samples/keepalived.conf.SSL_GET
/usr/share/doc/keepalived/samples/keepalived.conf.UDP_CHECK
/usr/share/doc/keepalived/samples/keepalived.conf.conditional_conf
/usr/share/doc/keepalived/samples/keepalived.conf.fwmark
/usr/share/doc/keepalived/samples/keepalived.conf.inhibit
/usr/share/doc/keepalived/samples/keepalived.conf.misc_check
/usr/share/doc/keepalived/samples/keepalived.conf.misc_check_arg
/usr/share/doc/keepalived/samples/keepalived.conf.quorum
/usr/share/doc/keepalived/samples/keepalived.conf.sample # Ubuntu装完keepalived默认没有配置文件,要把keepalived.conf.sample文件复制到相应的位置。
/usr/share/doc/keepalived/samples/keepalived.conf.status_code
/usr/share/doc/keepalived/samples/keepalived.conf.track_interface
/usr/share/doc/keepalived/samples/keepalived.conf.virtual_server_group
/usr/share/doc/keepalived/samples/keepalived.conf.virtualhost
/usr/share/doc/keepalived/samples/keepalived.conf.vrrp
/usr/share/doc/keepalived/samples/keepalived.conf.vrrp.localcheck
/usr/share/doc/keepalived/samples/keepalived.conf.vrrp.lvs_syncd
/usr/share/doc/keepalived/samples/keepalived.conf.vrrp.routes
/usr/share/doc/keepalived/samples/keepalived.conf.vrrp.rules
/usr/share/doc/keepalived/samples/keepalived.conf.vrrp.scripts
/usr/share/doc/keepalived/samples/keepalived.conf.vrrp.static_ipaddress
/usr/share/doc/keepalived/samples/keepalived.conf.vrrp.sync
/usr/share/doc/keepalived/samples/sample.misccheck.smbcheck.sh
/usr/share/doc/keepalived/samples/sample_notify_fifo.sh
/usr/share/man
/usr/share/man/man1
/usr/share/man/man1/genhash.1.gz
/usr/share/man/man5
/usr/share/man/man5/keepalived.conf.5.gz
/usr/share/man/man8
/usr/share/man/man8/keepalived.8.gz
/usr/share/snmp
/usr/share/snmp/mibs
/usr/share/snmp/mibs/KEEPALIVED-MIB.txt
/usr/share/snmp/mibs/VRRP-MIB.txt
/usr/share/snmp/mibs/VRRPv3-MIB.txt
/usr/bin/genhash

root@ubuntu2204:~# cp /usr/share/doc/keepalived/samples/keepalived.conf.sample /etc/keepalived/keepalived.conf

root@ubuntu2204:~# systemctl start keepalived
root@ubuntu2204:~# systemctl status keepalived
● keepalived.service - Keepalive Daemon (LVS and VRRP)
     Loaded: loaded (/lib/systemd/system/keepalived.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2024-01-19 19:20:02 CST; 3s ago
   Main PID: 1661 (keepalived)
      Tasks: 3 (limit: 2178)
     Memory: 4.1M
        CPU: 33ms
     CGroup: /system.slice/keepalived.service
             ├─1661 /usr/sbin/keepalived --dont-fork
             ├─1662 /usr/sbin/keepalived --dont-fork
             └─1664 /usr/sbin/keepalived --dont-fork

Jan 19 19:20:02 ubuntu2204 systemd[1]: keepalived.service: Got notification message from PID 1662, but reception only p>
Jan 19 19:20:02 ubuntu2204 Keepalived[1661]: Starting VRRP child process, pid=1664
Jan 19 19:20:02 ubuntu2204 systemd[1]: keepalived.service: Got notification message from PID 1664, but reception only p>
Jan 19 19:20:02 ubuntu2204 Keepalived[1661]: Startup complete
Jan 19 19:20:02 ubuntu2204 systemd[1]: Started Keepalive Daemon (LVS and VRRP).
Jan 19 19:20:02 ubuntu2204 Keepalived_vrrp[1664]: (VI_1) Entering BACKUP STATE (init)
Jan 19 19:20:02 ubuntu2204 Keepalived_healthcheckers[1662]: Gained quorum 1+0=1 <= 1 for VS [10.10.10.2]:tcp:1358
Jan 19 19:20:02 ubuntu2204 Keepalived_healthcheckers[1662]: Activating healthchecker for service [192.168.200.2]:tcp:13>
Jan 19 19:20:02 ubuntu2204 Keepalived_healthcheckers[1662]: Activating BFD healthchecker
Jan 19 19:20:06 ubuntu2204 Keepalived_vrrp[1664]: (VI_1) Entering MASTER STATE

root@ubuntu2204:~# ps auxf |grep keepalived
root        1674  0.0  0.1   7004  2168 pts/0    S+   19:20   0:00          \_ grep --color=auto keepalived
root        1661  0.0  0.5  28964  9992 ?        Ss   19:20   0:00 /usr/sbin/keepalived --dont-fork
root        1662  0.0  0.1  29088  3448 ?        S    19:20   0:00  \_ /usr/sbin/keepalived --dont-fork
root        1664  0.0  0.1  28964  3364 ?        S    19:20   0:00  \_ /usr/sbin/keepalived --dont-fork

2.3 编译安装

# Rocky和CentOS 9
yum -y install make gcc ipvsadm autoconf automake openssl-devel libnl3-devel iptables-devel ipset file net-snmp-devel glib2-devel pcre2-devel libnftnl libmnl systemd-devel

# Rocky 8和CentOS 8要启用powertools镜像仓库
dnf config-manager --set-enabled powertools

# 或者添加Rocky 8的powertools镜像仓库
cat > /etc/yum.repos.d/PowerTools.repo <<-EOF
[PowerTools]
name=PowerTools
baseurl=https://mirrors.sjtug.sjtu.edu.cn/rocky/\$releasever/PowerTools/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
EOF

# 或者添加CentOS 8的powertools镜像仓库
cat > /etc/yum.repos.d/PowerTools.repo <<-EOF
[PowerTools]
name=PowerTools
baseurl=https://mirrors.aliyun.com/centos/\$stream/PowerTools/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
EOF

# Rocky和CentOS 8
yum -y install make gcc ipvsadm autoconf automake openssl-devel libnl3-devel iptables-devel ipset-devel file-devel net-snmp-devel glib2-devel pcre2-devel libnftnl-devel libmnl-devel systemd-devel

# CentOS 7
yum -y install make gcc libnfnetlink-devel libnfnetlink ipvsadm libnl libnl-devel libnl3 libnl3-devel lm_sensors-libs net-snmp-agent-libs net-snmp-libs openssh-server openssh-clients openssl openssl-devel automake iproutel

# Ubuntu 20.04/22.04
apt update
apt -y install make gcc ipvsadm build-essential pkg-config automake autoconf libipset-dev libnl-3-dev libnl-genl-3-dev libssl-dev libxtables-dev libip4tc-dev libip6tc-dev libipset-dev libmagic-dev libsnmp-dev libglib2.0-dev libpcre2-dev libnftnl-dev libmnl-dev libsystemd-dev

# Ubuntu 18.04
apt update
apt -y install make gcc ipvsadm build-essential pkg-config automake autoconf iptables-dev libipset-dev libnl-3-dev libnl-genl-3-dev libssl-dev libxtables-dev libip4tc-dev libip6tc-dev libipset-dev libmagic-dev libsnmp-dev libglib2.0-dev libpcre2-dev libnftnl-dev libmnl-dev libsystemd-dev

[root@rocky9-2 ~]# wget https://keepalived.org/software/keepalived-2.2.8.tar.gz
-bash: wget: command not found
# Rocky和CentOS默认没有安装wget工具

# 安装wget工具
[root@rocky9-2 ~]# dnf -y install wget

[root@rocky9-2 ~]# wget https://keepalived.org/software/keepalived-2.2.8.tar.gz

[root@rocky9-2 ~]# tar xvf keepalived-2.2.8.tar.gz -C /usr/local/src/

[root@rocky9-2 ~]# cd /usr/local/src/keepalived-2.2.8/

# 选项--disable-fwmark 可用于禁用iptables规则,可防止VIP无法访问,无此选项默认会启用ipatbles规则
[root@rocky9-2 keepalived-2.2.8]# ./configure --prefix=/apps/keepalived --disable-fwmark

# -j 2 代表同时2个CPU参与编译
[root@rocky9-2 keepalived-2.2.8]# make -j 2 && make install

[root@rocky9-2 keepalived-2.2.8]# cd 
[root@rocky9-2 ~]# /apps/keepalived/sbin/keepalived -v
Keepalived v2.2.8 (04/04,2023), git commit v2.2.7-154-g292b299e+

Copyright(C) 2001-2023 Alexandre Cassen, <acassen@gmail.com>

Built with kernel headers for Linux 5.14.0
Running on Linux 5.14.0-362.8.1.el9_3.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Nov 8 17:36:32 UTC 2023
Distro: Rocky Linux 9.3 (Blue Onyx)

configure options: --prefix=/apps/keepalived --disable-fwmark

Config options:  LVS VRRP VRRP_AUTH VRRP_VMAC OLD_CHKSUM_COMPAT INIT=systemd SYSTEMD_NOTIFY

System options:  VSYSLOG MEMFD_CREATE IPV6_MULTICAST_ALL IPV4_DEVCONF LIBNL3 RTA_ENCAP RTA_EXPIRES RTA_NEWDST RTA_PREF FRA_SUPPRESS_PREFIXLEN FRA_SUPPRESS_IFGROUP FRA_TUN_ID RTAX_CC_ALGO RTAX_QUICKACK RTEXT_FILTER_SKIP_STATS FRA_L3MDEV FRA_UID_RANGE RTAX_FASTOPEN_NO_COOKIE RTA_VIA FRA_PROTOCOL FRA_IP_PROTO FRA_SPORT_RANGE FRA_DPORT_RANGE RTA_TTL_PROPAGATE IFA_FLAGS LWTUNNEL_ENCAP_MPLS LWTUNNEL_ENCAP_ILA NET_LINUX_IF_H_COLLISION LIBIPTC_LINUX_NET_IF_H_COLLISION LIBIPVS_NETLINK IPVS_DEST_ATTR_ADDR_FAMILY IPVS_SYNCD_ATTRIBUTES IPVS_64BIT_STATS IPVS_TUN_TYPE IPVS_TUN_CSUM IPVS_TUN_GRE VRRP_IPVLAN IFLA_LINK_NETNSID GLOB_BRACE GLOB_ALTDIRFUNC INET6_ADDR_GEN_MODE VRF

# 默认会自动生成unit文件
[root@rocky9-2 ~]# cat /usr/lib/systemd/system/keepalived.service 
[Unit]
Description=LVS and VRRP High Availability Monitor
After=network-online.target syslog.target 
Wants=network-online.target 
Documentation=man:keepalived(8)
Documentation=man:keepalived.conf(5)
Documentation=man:genhash(1)
Documentation=https://keepalived.org

[Service]
Type=notify
PIDFile=/run/keepalived.pid
KillMode=process
EnvironmentFile=-/apps/keepalived/etc/sysconfig/keepalived
ExecStart=/apps/keepalived/sbin/keepalived --dont-fork $KEEPALIVED_OPTIONS
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target

[root@rocky9-2 ~]# cat /apps/keepalived/etc/sysconfig/keepalived
# Options for keepalived. See `keepalived --help' output and keepalived(8) and
# keepalived.conf(5) man pages for a list of all options. Here are the most
# common ones :
#
# --vrrp               -P    Only run with VRRP subsystem.
# --check              -C    Only run with Health-checker subsystem.
# --dont-release-vrrp  -V    Dont remove VRRP VIPs & VROUTEs on daemon stop.
# --dont-release-ipvs  -I    Dont remove IPVS topology on daemon stop.
# --dump-conf          -d    Dump the configuration data.
# --log-detail         -D    Detailed log messages.
# --log-facility       -S    0-7 Set local syslog facility (default=LOG_DAEMON)
#

KEEPALIVED_OPTIONS="-D"

# 默认无法启动
[root@rocky9-2 ~]# systemctl start keepalived
Job for keepalived.service failed because the control process exited with error code.
See "systemctl status keepalived.service" and "journalctl -xeu keepalived.service" for details.

[root@rocky9-2 ~]# tail -f /var/log/messages
Jan 19 21:14:22 rocky9-2 Keepalived[27384]: Command line: '/apps/keepalived/sbin/keepalived' '--dont-fork' '-D'
Jan 19 21:14:22 rocky9-2 Keepalived[27384]: Config files missing '/apps/keepalived/etc/keepalived/keepalived.conf'.
# 不能启动的原因就是“/apps/keepalived/etc/keepalived/keepalived.conf”配置文件丢失

[root@rocky9-2 ~]# mkdir -p /etc/keepalived

NET_NAME=`ip a |awk -F"[: ]" '/^2/{print $3}'`

cat > /etc/keepalived/keepalived.conf <<EOF
! 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 LVS_DEVEL
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_instance VI_1 {
    state MASTER
    interface ${NET_NAME}
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        172.31.0.180 dev ${NET_NAME} label ${NET_NAME}:0
    }
}
EOF

# keepalived.conf配置文件详解
[root@rocky9-2 ~]# cat /etc/keepalived/keepalived.conf 
! Configuration File for keepalived

# global是全局配置
global_defs {
   notification_email { # keepalived 发生故障切换时邮件发送的目标邮箱,可以按行区分写多个
     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 # 邮件服务器连接timeout
   router_id LVS_DEVEL # 每个keepalived主机唯一标识,建议使用当前主机名,如果多节点重名可能会影响切换脚本执行
   vrrp_skip_check_adv_addr # 对所有通告报文都检查,会比较消耗性能,启用此配置后,如果收到的通告报文和上一个报文是同一个路由器,则跳过检查,默认值为全检查
   vrrp_strict # 严格遵守VRRP协议,启用此项后以下状况将无法启动服务:1.无VIP地址 2.配置了单播邻居 3.在VRRP版本2中有IPv6地址,开启动此项并且没有配置vrrp_iptables时会自动开启iptables防火墙规则,默认导致VIP无法访问,建议不加此项配置
   vrrp_garp_interval 0 # gratuitous ARP messages 报文发送延迟,0表示不延迟
   vrrp_gna_interval 0 # unsolicited NA messages (不请自来)消息发送延迟
   vrrp_mcast_group4 224.0.0.18 #指定组播IP地址范围:224.0.0.0到239.255.255.255,默认值:224.0.0.18
   vrrp_iptables #此项和vrrp_strict同时开启时,则不会添加防火墙规则,如果无配置vrrp_strict项,则无需启用此项配置
}

# 配置虚拟路由器
vrrp_instance VI_1 { # VI_1为vrrp的实例名,一般为业务名称
    state MASTER|BACKUP # 当前节点在此虚拟路由器上的初始状态,状态为MASTER或者BACKUP
    interface ens160 # 绑定为当前虚拟路由器使用的物理接口,如:eth0,bond0,br0,可以和VIP不在一个网卡
    virtual_router_id 51 # 每个虚拟路由器惟一标识,范围:0-255,每个虚拟路由器此值必须唯一,否则服务无法启动,同属一个虚拟路由器的多个keepalived节点必须相同,务必要确认在同一网络中此值必须唯
    priority 100 # 当前物理节点在此虚拟路由器的优先级,范围:1-254,值越大优先级越高,每个keepalived主机节点此值不同
    advert_int 1 # vrrp通告的时间间隔,默认1s
    authentication { # 认证机制
        auth_type AH|PASS # AH为IPSEC认证(不推荐),PASS为简单密码(建议使用)
        auth_pass 1111 # 预共享密钥,仅前8位有效,同一个虚拟路由器的多个keepalived节点必须一样
    }
    virtual_ipaddress { # 虚拟IP,生产环境可能指定上百个IP地址
        192.168.200.100 # 指定VIP,不指定网卡,默认为eth0,注意:不指定/prefix,默认为/32
        192.168.200.101/24 dev eth1 # 指定VIP的网卡,建议和interface指令指定的岗卡不在一个网卡
        172.31.0.180 dev ens160 label ens160:0 # 指定VIP的网卡label 
    }
    track_interface { #配置监控网络接口,一旦出现故障,则转为FAULT状态实现地址转移
        eth0
        eth1
        …
    }
}

[root@rocky9-2 ~]# systemctl start keepalived
# 再次启动成功

[root@rocky9-2 ~]# systemctl status keepalived
● keepalived.service - LVS and VRRP High Availability Monitor
     Loaded: loaded (/usr/lib/systemd/system/keepalived.service; enabled; preset: disabled)
     Active: active (running) since Fri 2024-01-19 22:00:18 CST; 1min 5s ago
       Docs: man:keepalived(8)
             man:keepalived.conf(5)
             man:genhash(1)
             https://keepalived.org
   Main PID: 28043 (keepalived)
      Tasks: 2 (limit: 10840)
     Memory: 1.2M
        CPU: 22ms
     CGroup: /system.slice/keepalived.service
             ├─28043 /apps/keepalived/sbin/keepalived --dont-fork -D
             └─28044 /apps/keepalived/sbin/keepalived --dont-fork -D

Jan 19 22:01:15 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:16 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:17 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:18 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:19 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:20 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:21 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:22 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:23 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!
Jan 19 22:01:24 rocky9-2 Keepalived_vrrp[28044]: (VI_1) received an unexpected ip number count 3, expected 2!

[root@rocky9-2 ~]# hostname -i
172.31.0.19 172.31.0.180
[root@rocky9-2 ~]# ip addr
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: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:a3:9f:06 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 172.31.0.19/21 brd 172.31.7.255 scope global noprefixroute ens160
       valid_lft forever preferred_lft forever
    inet 172.31.0.180/32 scope global ens160:0
       valid_lft forever preferred_lft forever
    inet6 fe80::e43b:12f1:1f9e:55fc/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

[root@rocky9-2 ~]# ping 172.31.0.180
PING 172.31.0.180 (172.31.0.180) 56(84) bytes of data.
64 bytes from 172.31.0.180: icmp_seq=1 ttl=64 time=0.029 ms
64 bytes from 172.31.0.180: icmp_seq=2 ttl=64 time=0.101 ms
^C
--- 172.31.0.180 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1010ms
rtt min/avg/max/mdev = 0.029/0.065/0.101/0.036 ms

[root@rocky9-2 ~]# iptables -vnL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

2.4 一键编译安装keepalived脚本

Shell脚本源码地址:

Gitee:https://gitee.com/raymond9/shell

Github:https://github.com/raymond999999/shell

可以去上面的Gitee或Github代码仓库拉取脚本。

[root@rocky9 ~]# cat install_keepalived_v2.sh 
#!/bin/bash
#
#************************************************************************************************************
#Author:        Raymond
#QQ:            88563128
#Date:          2024-01-26
#FileName:      install_keepalived_v2.sh
#URL:           raymond.blog.csdn.net
#Description:   install_keepalived for CentOS 7 & CentOS Stream 8/9 & Ubuntu 18.04/20.04/22.04 & Rocky 8/9
#Copyright (C): 2024 All rights reserved
#************************************************************************************************************
SRC_DIR=/usr/local/src
COLOR="echo -e \\033[01;31m"
END='\033[0m'
KEEPALIVED_URL=https://keepalived.org/software/
KEEPALIVED_FILE=keepalived-2.2.8.tar.gz
KEEPALIVED_INSTALL_DIR=/apps/keepalived
CPUS=`lscpu |awk '/^CPU\(s\)/{print $2}'`
NET_NAME=`ip a |awk -F"[: ]" '/^2/{print $3}'`
VIP=172.31.0.180

os(){
    OS_ID=`sed -rn '/^NAME=/s@.*="([[:alpha:]]+).*"$@\1@p' /etc/os-release`
    OS_RELEASE_VERSION=`sed -rn '/^VERSION_ID=/s@.*="?([0-9]+)\.?.*"?@\1@p' /etc/os-release`
}

check_file (){
    cd  ${SRC_DIR}
    if [ ${OS_ID} == "CentOS" -o ${OS_ID} == "Rocky" ] &> /dev/null;then
        rpm -q wget &> /dev/null || { ${COLOR}"安装wget工具,请稍等..."${END};yum -y install wget &> /dev/null; }
    fi
    if [ ! -e ${KEEPALIVED_FILE} ];then
        ${COLOR}"缺少${KEEPALIVED_FILE}文件,如果是离线包,请放到${SRC_DIR}目录下"${END}
        ${COLOR}'开始下载Keepalived源码包'${END}
        wget ${KEEPALIVED_URL}${KEEPALIVED_FILE} || { ${COLOR}"Keepalived源码包下载失败"${END}; exit; }
    else
        ${COLOR}"${KEEPALIVED_FILE}文件已准备好"${END}
    fi
}

install_keepalived(){
    ${COLOR}"开始安装Keepalived,请稍等..."${END}
    ${COLOR}"开始安装Keepalived依赖包,请稍等..."${END}
    if [ ${OS_ID} == "Rocky" -a ${OS_RELEASE_VERSION} == 8 ];then
        MIRROR=mirrors.sjtug.sjtu.edu.cn
        if [ `grep -R "\[powertools\]" /etc/yum.repos.d/*.repo` ];then
            dnf config-manager --set-enabled powertools
        else
            cat > /etc/yum.repos.d/PowerTools.repo <<-EOF
[PowerTools]
name=PowerTools
baseurl=https://${MIRROR}/rocky/\$releasever/PowerTools/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rockyofficial
EOF
        fi
    fi
    if [ ${OS_ID} == "CentOS" -a ${OS_RELEASE_VERSION} == 8 ];then
        MIRROR=mirrors.aliyun.com
        if [ `grep -R "\[powertools\]" /etc/yum.repos.d/*.repo` ];then
            dnf config-manager --set-enabled powertools
        else
            cat > /etc/yum.repos.d/PowerTools.repo <<-EOF
[PowerTools]
name=PowerTools
baseurl=https://${MIRROR}/centos/\$stream/PowerTools/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
EOF
        fi
    fi
    if [ ${OS_RELEASE_VERSION} == 9 ];then
        yum -y install make gcc ipvsadm autoconf automake openssl-devel libnl3-devel iptables-devel ipset file net-snmp-devel glib2-devel pcre2-devel libnftnl libmnl systemd-devel &> /dev/null
    elif [ ${OS_RELEASE_VERSION} == 8 ];then	
        yum -y install make gcc ipvsadm autoconf automake openssl-devel libnl3-devel iptables-devel ipset-devel file-devel net-snmp-devel glib2-devel pcre2-devel libnftnl-devel libmnl-devel systemd-devel &> /dev/null
    elif [ ${OS_RELEASE_VERSION} == 7 ];then
        yum -y install make gcc libnfnetlink-devel libnfnetlink ipvsadm libnl libnl-devel libnl3 libnl3-devel lm_sensors-libs net-snmp-agent-libs net-snmp-libs openssh-server openssh-clients openssl openssl-devel automake iproute &> /dev/null
    elif [ ${OS_RELEASE_VERSION} == "20" -o ${OS_RELEASE_VERSION} == "22" ];then
        apt update &> /dev/null;apt -y install make gcc ipvsadm build-essential pkg-config automake autoconf libipset-dev libnl-3-dev libnl-genl-3-dev libssl-dev libxtables-dev libip4tc-dev libip6tc-dev libipset-dev libmagic-dev libsnmp-dev libglib2.0-dev libpcre2-dev libnftnl-dev libmnl-dev libsystemd-dev
    else
        apt update &> /dev/null;apt -y install make gcc ipvsadm build-essential pkg-config automake autoconf iptables-dev libipset-dev libnl-3-dev libnl-genl-3-dev libssl-dev libxtables-dev libip4tc-dev libip6tc-dev libipset-dev libmagic-dev libsnmp-dev libglib2.0-dev libpcre2-dev libnftnl-dev libmnl-dev libsystemd-dev &> /dev/null
    fi
    tar xf ${KEEPALIVED_FILE}
    KEEPALIVED_DIR=`echo ${KEEPALIVED_FILE} | sed -nr 's/^(.*[0-9]).*/\1/p'`
    cd ${KEEPALIVED_DIR}
    ./configure --prefix=${KEEPALIVED_INSTALL_DIR} --disable-fwmark
    make -j $CPUS && make install
    [ $? -eq 0 ] && $COLOR"Keepalived编译安装成功"$END ||  { $COLOR"Keepalived编译安装失败,退出!"$END;exit; }
    [ -d /etc/keepalived ] || mkdir -p /etc/keepalived &> /dev/null
    read -p "请输入是主服务端或备用服务端,例如(MASTER或BACKUP): " STATE
    read -p "请输入优先级,例如(100或80): " PRIORITY
    cat > /etc/keepalived/keepalived.conf <<EOF
! 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 LVS_DEVEL
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}

vrrp_instance VI_1 {
    state ${STATE}
    interface ${NET_NAME}
    virtual_router_id 51
    priority ${PRIORITY}
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        ${VIP} dev ${NET_NAME} label ${NET_NAME}:1   
    }
}
EOF
    cp ./keepalived/keepalived.service /lib/systemd/system/
    echo "PATH=${KEEPALIVED_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/keepalived.sh
    systemctl daemon-reload
    systemctl enable --now keepalived &> /dev/null 
    systemctl is-active keepalived &> /dev/null ||  { ${COLOR}"Keepalived 启动失败,退出!"${END} ; exit; }
    ${COLOR}"Keepalived安装完成"${END}
}

main(){
    os
    check_file
    install_keepalived
}

main

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/409774.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

在autodl搭建stable-diffusion-webui+sadTalker

本文介绍在autodl.com搭建gpu服务器&#xff0c;实现stable-diffusion-webuisadTalker功能&#xff0c;图片音频 可生成视频。 autodl租GPU 自己本地部署SD环境会遇到各种问题&#xff0c;网络问题&#xff08;比如huggingface是无法访问&#xff09;&#xff0c;所以最好的方…

元学习(meta-learning)的通俗解释

目录 1、什么是元学习 2、元学习还可以做什么 3、元学习是如何训练的 1、什么是元学习 meta-learning 的一个很经典的英文解释是 learn to learn&#xff0c;即学会学习。元学习是一个很宽泛的概念&#xff0c;可以有很多实现的方式&#xff0c;下面以目标检测的例子来解释…

macOS系统下载IDEA的操作流程

第一步 进入官网 Download IntelliJ IDEA – The Leading Java and Kotlin IDE 第二步 根据mac的芯片选择版本下载 芯片的查看位置是【设置】-【通用】-【关于本机】-第二个&#xff0c;我的是Apple芯片&#xff0c;选Apple Silicon -- 第三步 右上角下载处打开安装包&…

485隔离器4口集线器一分二四路导轨安装数字量输入模块RS485中继

品牌&#xff1a;泰工华控 型号&#xff1a;TD-7511/TD-7512/TD-7514 产地&#xff1a;中国大陆 省份&#xff1a;安徽省 地址&#xff1a;宿州市 颜色分类&#xff1a;485一进一出隔离,485缓存器一进二出&#xff08;两主一从,485分路器一进二出&#xff08;一主两从&…

[C++][C++11][四] -- [lambda表达式]

目录 1.为什么要有lambda表达式&#xff1f;2.lambda表达式3.lambda表达式语法4.函数对象与lambda表达式 1.为什么要有lambda表达式&#xff1f; 在C98中&#xff0c;如果想要对一个数据集合中的元素进行排序&#xff0c;可以使用std::sort方法 如果待排序元素为自定义类型&am…

<网络安全>《52 网络攻防专业课<第十五课 - 跳板>

1 跳板技术 当攻击者入侵被攻击者时&#xff0c;被攻击者可以根据IP地址追踪攻击者来自哪里。 攻击者为了隐藏自己的真正IP&#xff0c;通常会采用跳板&#xff0c;如右图&#xff0c; 攻击者通过2个跳板攻击被攻击者。即使被攻击者进行反向追踪&#xff0c;也只能追踪到攻击…

【Activiti7系列】Activi7简介和基于Spring Boot整合Activiti7(流程设计器)

本文将介绍Activiti7基础概念及基于Spring Boot整合Activiti7(流程设计器)的具体步骤。 作者&#xff1a;后端小肥肠 1. 前言 在企业级应用中&#xff0c;业务流程的管理和执行是至关重要的一环。Activiti7是一个强大的开源工作流引擎&#xff0c;它提供了灵活的流程定义、任务…

机器学习.线性回归

斯塔1和2是权重项&#xff0c;斯塔0是偏置项&#xff0c;在训练过程中为了使得训练结果更加精确而做的微调&#xff0c;不是一个大范围的因素&#xff0c;核心影响因素是权重项 为了完成矩阵的运算&#xff0c;在斯塔0后面乘x0&#xff0c;使得满足矩阵的转换&#xff0c;所以在…

HTTP---------状态码

当服务端返回 HTTP 响应时&#xff0c;会带有一个状态码&#xff0c;用于表示特定的请求结果。比如 HTTP/1.1 200 OK&#xff0c;里面的 HTTP/1.1 表示协议版本&#xff0c;200 则是状态码&#xff0c;OK 则是对状态码的描述。 由协议版本、状态码、描述信息组成的行被称为起始…

文献阅读:Transformers are Multi-State RNNs

文献阅读&#xff1a;Transformers are Multi-State RNNs 1. 内容简介2. 方法介绍 1. 基础回顾 1. RNN2. Transformer 2. Transformer解构 1. MSRNN2. Transformer 3. TOVA 1. 现有转换策略2. TOVA 3. 实验考察 & 结论 1. 实验设计2. 实验结果 1. LM2. 长文本理解3. 文本生…

win7系统安装.net 4.7.2失败的解决办法

1、提示如下错误时导入证书MicrosoftRootCertificateAuthority2011.cer&#xff0c;具体可以从网上搜&#xff1a; 2、导入证书后再次重试&#xff0c;提示如下错误&#xff1a; 这时可能是缺少系统补丁&#xff0c;安装补丁&#xff1a;Windows6.1-KB2813430-x64.msu。安装完要…

Seata分布式事务实战XATCC模式

目录 XA模式 XA 模式的使用 Spring Cloud Alibaba整合Seata XA TCC模式 TCC模式接口改造 TCC如何控制异常 Spring Cloud Alibaba整合Seata TCC XA模式 整体机制 在 Seata 定义的分布式事务框架内&#xff0c;利用事务资源&#xff08;数据库、消息服务等&#xff09;对…

力扣--哈希表/滑动窗口/双指针3.无重复字符的最长子串

思路分析&#xff1a; 使用双指针 i 和 j 表示子串的起始位置和结束位置。遍历字符串 s&#xff0c;对于每个字符&#xff1a; 如果字符不在 hash 中&#xff0c;将其加入 hash&#xff0c;同时更新最长子串的长度 result。如果字符已经在 hash 中&#xff0c;说明有重复字符出…

力扣LCR 140. 训练计划 II(顺序遍历,快慢指针)

Problem: LCR 140. 训练计划 II 文章目录 题目描述思路复杂度Code 题目描述 思路 思路1&#xff1a;顺序遍历 欲返回倒数第cnt个节点则需要顺序遍历到len-cnt&#xff08;其中len为链表的长度&#xff09; 思路2&#xff1a;快慢指针 让一个快指针fast指向cnt 1个节点&#x…

Java的File常用方法【详解】

目录 1.概念 2.创建对象 3.常用方法1&#xff1a;判断文件类型、获取文件信息 4.常用方法2&#xff1a;创建文件、删除文件 5.常用方法3&#xff1a;遍历文件夹 1.概念 File是java.io.包下的类&#xff0c; File类的对象&#xff0c;用于代表当前操作系统的文件&#xff0…

Java 面向对象进阶 18 JDK8、9开始新增的方法;接口的应用;适配器设计模式;内部类(黑马)

一、JDK8开始新增的方法 默认方法不是抽象方法&#xff0c;所以不强制被重写&#xff1a; 但是如果被重写&#xff0c;就要去掉default关键字&#xff1a; public可以省略&#xff0c;但是default不可以省略&#xff1a; public是灰色的&#xff0c;代表可以省略 但是default是…

pclpy 最小二乘法拟合平面

pclpy 最小二乘法拟合平面 一、算法原理二、代码三、结果1.左边原点云、右边最小二乘法拟合平面后点云投影 四、相关数据 一、算法原理 平面方程的一般表达式为&#xff1a; A x B y C z D 0 ( C ≠ 0 ) Ax By Cz D 0 \quad (C\neq0) AxByCzD0(C0) 即&#xff1a; …

【深度学习笔记】3_14 正向传播、反向传播和计算图

3.14 正向传播、反向传播和计算图 前面几节里我们使用了小批量随机梯度下降的优化算法来训练模型。在实现中&#xff0c;我们只提供了模型的正向传播&#xff08;forward propagation&#xff09;的计算&#xff0c;即对输入计算模型输出&#xff0c;然后通过autograd模块来调…

Nest.js权限管理系统开发(五)返回格式化

返回格式化拦截器 在上一篇《Nest.js权限管理系统开发&#xff08;四&#xff09;Swagger API接入》中&#xff0c;我们在base.controller.ts中创建了多个接口&#xff0c;每个接口都有不同的返回类型。现实中我们往往需要统一返回数据的格式&#xff0c;例如&#xff1a; {&…

【零基础】VOSviewer小白入门第一课

官网安装&#xff1a;VOSviewer - Visualizing scientific landscapes 安装完成后即可以打开VOSviewer: 在 wos of science 中搜索关键词&#xff1a;lawdata 选择导出&#xff0c;按照plain text file格式导出&#xff0c;可以到处1000个。选择all record 得到下图 读取vosvi…