Keepalived介绍、架构和安装

news2024/12/23 9:45:01

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

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

分享一个UE的SmoothStep小技巧

SmoothStep节点可以制作更平滑的动画&#xff0c;而如果将max参数作为值传入将value和min参数作为约束&#xff0c;则可以做出类似冲击波的渐变效果&#xff1a; 并且通过修改value与min之间的数值差&#xff0c;可以调节渐变。 这个技巧主要就是可以产生硬边。 比如我们可…

Django——ORM增删改查

基本对象 model.objects 创建数据 可以通过django编写的命令行方式快捷创建数据 python manage.py shell 如果对模型层有任何修改都需要重启shell&#xff0c;否则操作容易出错 在shell中我们需要先引入我们的模型&#xff0c;如from bookstore.models import Book 然后通过…

套接字与套接字编程

对于刚刚学习计算机网络&#xff1a;自顶向下的同学们&#xff0c;在观看了中科大的视频---TCP Socket以及UDP Socket会感到些许疑惑&#xff0c;不过没事&#xff0c;在这篇小文章将会为你解开Socket的神秘面纱 什么是Socket&#xff1f;: Socket 是一套用于不同主机之间通信…

2024年面试季,大前端相关开发者不妨了解一下鸿蒙开发岗

搜狐&#xff1a;我宣布与华为达成鸿蒙全面合作&#xff01; 美团&#xff1a;我宣布与华为达成鸿蒙全面合作&#xff01; 360 &#xff1a;我宣布与华为达成鸿蒙全面合作&#xff01; 高德&#xff1a;我宣布与华为达成鸿蒙全面合作&#xff01; 新浪&#xff1a;我宣布与华为…

java——特殊文件日志技术

目录 特殊文件Properties文件XML文件XML文件有如下的特点XML的作用和应用场景解析XML文件 日志技术概述日志技术的体系结构Logback日志框架概述快速入门核心配置文件logback.xml日志级别项目中使用日志框架 特殊文件 Properties文件 后缀为.properties的文件&#xff0c;称之…

探索D咖智能饮品机器人的工作原理:科技、材料与设计的相互融合

智能饮品机器人是近年来随着人工智能和自动化技术的发展而崭露头角的一种创新产品。它将科技、材料和设计相互融合&#xff0c;为消费者带来了全新的饮品体验。下面D咖来探索智能饮品机器人的工作原理&#xff0c;以及科技、材料和设计在其中的作用。 首先&#xff0c;智能饮品…

悄悄话花费的时间(C语言)

题目描述 给定一个二叉树&#xff0c;每个节点上站着一个人&#xff0c;节点数字表示父节点到该节点传递悄悄话需要花费的时间。 初始时&#xff0c;根节点所在位置的人有一个悄悄话想要传递给其他人&#xff0c;求二叉树所有节点上的人都接收到悄悄话花费的时间。 输入描述 …

企业统一身份中台,如何比传统单点登录SSO做得更好?

传统的单点登录SSO方案往往仅解决以下问题&#xff1a;多应用系统入口不统一&#xff0c;导致员工需要切换多个登录地址&#xff0c;重复多次登录&#xff0c;极大影响业务访问效率及员工登录体验。随着IT基础设施的增多&#xff0c;企业对全场景&#xff08;如网络、VPN、云桌…

Jmeter基础(2) 目录介绍

目录 Jmeter目录介绍bin目录docsextrasliblicensesprintable_docs Jmeter目录介绍 在学习Jmeter之前&#xff0c;需要先对工具的目录有些了解&#xff0c;也会方便后续的学习 bin目录 examplesCSV目录中有CSV样例jmeter.batwindow 启动文件jmeter.shMac/linux的启动文件jmete…

flink内存管理,设置思路,oom问题,一文全

flink内存管理 1 内存分配1.1 JVM 进程总内存&#xff08;Total Process Memory&#xff09;1.2 Flink 总内存&#xff08;Total Flink Memory&#xff09;1.3 JVM 堆外内存&#xff08;JVM Off-Heap Memory&#xff09;1.4 JVM 堆内存&#xff08;JVM Heap Memory&#xff09;…

如何在Pycharm中导入第三方库(以pyecharts为例子)

打开Pycharm 点击右上角文件->设置->项目->pythonProject&#xff08;Python解释器&#xff09; 点击下图号 下一步&#xff1a;在搜索栏中直接搜索第三方包pyecharts并安装即可 以上便为使用Pycharm安装第三方库的全过程。 温馨小提示&#xff0c;如果大家在Pychar…

研学活动报名平台系统功能清单

中小学生社会实践活动、研学旅行等素质教育活动报名与管理平台&#xff0c;功能包含&#xff1a;活动分类&#xff0c;活动管理&#xff0c;在线报名缴费&#xff0c;扫码核销&#xff0c;会员特权体系&#xff0c;在线商城&#xff0c;研学互动。系统支持入驻老师自行创建研学…

代码随想录算法训练营第二十六天|39. 组合总和、40.组合总和II、131.分割回文串

39. 组合总和 刷题https://leetcode.cn/problems/combination-sum/description/文章讲解https://programmercarl.com/0039.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C.html视频讲解https://www.bilibili.com/video/BV1KT4y1M7HJ/?vd_sourceaf4853e80f89e28094a5fe1e220d9062 回溯…

【数据分享】2014-2024年全国监测站点的逐年空气质量数据(15个指标\免费获取)

空气质量的好坏反映了空气的污染程度&#xff0c;在各项涉及城市环境的研究中&#xff0c;空气质量都是一个十分重要的指标。空气质量是依据空气中污染物浓度的高低来判断的。 我们发现学者王晓磊在自己的主页里面分享了2014年5月以来的全国范围的到站点的逐时空气质量数据&am…

【Python笔记-设计模式】组合模式

一、说明 组合模式是一种结构型设计模式&#xff0c; 你可以使用它将对象组合成树状结构&#xff0c; 并且能像使用独立对象一样使用它们。 (一) 解决问题 处理树形结构&#xff1a;可以很好地处理树形结构的数据&#xff0c;使得用户可以统一对待单个对象和对象组合。统一接…

【LeetCode每日一题】 单调栈的案例 42. 接雨水

这道题是困难&#xff0c;但是可以使用单调栈&#xff0c;非常简洁通俗。 关于单调栈可以参考单调栈总结以及Leetcode案例解读与复盘 42. 接雨水 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图&#xff0c;计算按此排列的柱子&#xff0c;下雨之后能接多少雨水。 示例 …

2 物理层(五):传输介质

目录 1 传输介质1.1 有线传输媒体1、双绞线2、同轴电缆3、光纤 1.2 无线传输媒体1、无线电波段分配2、微波通信3、卫星通信4、红外通信和激光通信 1 传输介质 物理层传输的二进制比特流需要在传输介质上实现。传输介质是数据传输的物理通道&#xff0c;它还能连接主机和各种网…

【JAVA】中的静态代理、动态代理以及CGLIB动态代理

目录 1.静态代理 2.动态代理 3.cglib代理 代理模式是java中最常用的设计模式之一&#xff0c;尤其是在spring框架中广泛应用。对于java的代理模式&#xff0c;一般可分为&#xff1a;静态代理、动态代理、以及CGLIB实现动态代理。 对于上述三种代理模式&#xff0c;分别进行…

Kubernetes 二进制部署 《easzlab / kubeasz项目部署》(一)

Kubernetes 二进制部署 - easzlab / kubeasz项目部署 1. 准备工作1.1 设置防火墙1.2 设置SeLinux1.3 设置时区及时间同步1.4 配置域名解析1.5 确认SSH开启1.6 IP转发1.7 安装docker1.8 关闭swap 2. 服务器规划2.1 基本架构图2.2 官方建议2.3 实践服务器规划 3. 服务器配置3.1 配…

基于MPPT最大功率跟踪算法的涡轮机控制系统simulink建模与仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序与模型 4.系统原理简介 5.完整工程文件 1.课题概述 基于MPPT最大功率跟踪算法的涡轮机控制系统simulink建模与仿真.mppt采用爬山法实现&#xff0c;仿真输出MPPT控制效果&#xff0c;功率&#xff0c;转速等。 2.系统仿真结果 …