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 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::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 1000link/ether 00:0c:29:37:62:95 brd ff:ff:ff:ff:ff:ffaltname enp3s0inet 172.31.0.9/21 brd 172.31.7.255 scope global noprefixroute ens160valid_lft forever preferred_lft foreverinet6 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 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::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 1000link/ether 00:0c:29:6f:65:d3 brd ff:ff:ff:ff:ff:ffaltname enp3s0altname ens160inet 172.31.0.8/21 brd 172.31.7.255 scope global noprefixroute eth0valid_lft forever preferred_lft foreverinet6 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/bashread -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}
EOFraymond@ubuntu2204:~$ bash set_root_login.sh 
请输入密码: 123456
[sudo] password for raymond: New password: Retype new password: passwd: password updated successfullyraymond@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: 2renderer: networkdethernets:eth0:dhcp4: nodhcp6: noaddresses: [172.31.0.20/21] gateway4: 172.31.0.2nameservers: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: 2renderer: networkdethernets:eth0:dhcp4: nodhcp6: noaddresses: [172.31.0.18/21] gateway4: 172.31.0.2nameservers: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 nowroot@ubuntu2004:~# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::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 1000link/ether 00:0c:29:e5:98:6f brd ff:ff:ff:ff:ff:ffinet 172.31.0.20/21 brd 172.31.7.255 scope global eth0valid_lft forever preferred_lft foreverinet6 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: 2renderer: networkdethernets:eth0:dhcp4: nodhcp6: noaddresses: [172.31.0.22/21]routes:- to: defaultvia: 172.31.0.2nameservers: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 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::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 1000link/ether 00:0c:29:a7:be:f2 brd ff:ff:ff:ff:ff:ffaltname enp2s1altname ens33inet 172.31.0.22/21 brd 172.31.7.255 scope global eth0valid_lft forever preferred_lft foreverinet6 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*.repodnf clean all && dnf makecache

CentOS Stream 9:

cat update_mirror.pl
#!/usr/bin/perluse 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*.repodnf 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-*.repodnf 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-*.repoyum 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.listapt 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.listSECURITY_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.listapt 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 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::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 1000link/ether 00:0c:29:37:62:95 brd ff:ff:ff:ff:ff:ffaltname enp3s0inet 172.31.0.9/21 brd 172.31.7.255 scope global noprefixroute ens160valid_lft forever preferred_lft foreverinet6 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 keepalivedroot@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 clusterskeepalived is used for monitoring real servers within a LinuxVirtual Server (LVS) cluster.  keepalived can be configured toremove real servers from the cluster pool if it stops responding,as well as send a notification email to make the admin aware ofthe service failure..In addition, keepalived implements an independent Virtual RouterRedundancy 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/genhashroot@ubuntu2204:~# cp /usr/share/doc/keepalived/samples/keepalived.conf.sample /etc/keepalived/keepalived.confroot@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 agoMain PID: 1661 (keepalived)Tasks: 3 (limit: 2178)Memory: 4.1MCPU: 33msCGroup: /system.slice/keepalived.service├─1661 /usr/sbin/keepalived --dont-fork├─1662 /usr/sbin/keepalived --dont-fork└─1664 /usr/sbin/keepalived --dont-forkJan 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 STATEroot@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-fwmarkConfig options:  LVS VRRP VRRP_AUTH VRRP_VMAC OLD_CHKSUM_COMPAT INIT=systemd SYSTEMD_NOTIFYSystem 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/keepalivedNET_NAME=`ip a |awk -F"[: ]" '/^2/{print $3}'`cat > /etc/keepalived/keepalived.conf <<EOF
! Configuration File for keepalivedglobal_defs {notification_email {acassen@firewall.locfailover@firewall.locsysadmin@firewall.loc}notification_email_from Alexandre.Cassen@firewall.locsmtp_server 192.168.200.1smtp_connect_timeout 30router_id LVS_DEVELvrrp_skip_check_adv_addrvrrp_strictvrrp_garp_interval 0vrrp_gna_interval 0
}vrrp_instance VI_1 {state MASTERinterface ${NET_NAME}virtual_router_id 51priority 100advert_int 1authentication {auth_type PASSauth_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.locfailover@firewall.locsysadmin@firewall.loc}notification_email_from Alexandre.Cassen@firewall.loc # 发邮件的地址smtp_server 192.168.200.1 # 邮件服务器地址smtp_connect_timeout 30 # 邮件服务器连接timeoutrouter_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.18vrrp_iptables #此项和vrrp_strict同时开启时,则不会添加防火墙规则,如果无配置vrrp_strict项,则无需启用此项配置
}# 配置虚拟路由器
vrrp_instance VI_1 { # VI_1为vrrp的实例名,一般为业务名称state MASTER|BACKUP # 当前节点在此虚拟路由器上的初始状态,状态为MASTER或者BACKUPinterface ens160 # 绑定为当前虚拟路由器使用的物理接口,如:eth0,bond0,br0,可以和VIP不在一个网卡virtual_router_id 51 # 每个虚拟路由器惟一标识,范围:0-255,每个虚拟路由器此值必须唯一,否则服务无法启动,同属一个虚拟路由器的多个keepalived节点必须相同,务必要确认在同一网络中此值必须唯priority 100 # 当前物理节点在此虚拟路由器的优先级,范围:1-254,值越大优先级越高,每个keepalived主机节点此值不同advert_int 1 # vrrp通告的时间间隔,默认1sauthentication { # 认证机制auth_type AH|PASS # AH为IPSEC认证(不推荐),PASS为简单密码(建议使用)auth_pass 1111 # 预共享密钥,仅前8位有效,同一个虚拟路由器的多个keepalived节点必须一样}virtual_ipaddress { # 虚拟IP,生产环境可能指定上百个IP地址192.168.200.100 # 指定VIP,不指定网卡,默认为eth0,注意:不指定/prefix,默认为/32192.168.200.101/24 dev eth1 # 指定VIP的网卡,建议和interface指令指定的岗卡不在一个网卡172.31.0.180 dev ens160 label ens160:0 # 指定VIP的网卡label }track_interface { #配置监控网络接口,一旦出现故障,则转为FAULT状态实现地址转移eth0eth1…}
}[root@rocky9-2 ~]# systemctl start keepalived
# 再次启动成功[root@rocky9-2 ~]# systemctl status keepalived
● keepalived.service - LVS and VRRP High Availability MonitorLoaded: loaded (/usr/lib/systemd/system/keepalived.service; enabled; preset: disabled)Active: active (running) since Fri 2024-01-19 22:00:18 CST; 1min 5s agoDocs: man:keepalived(8)man:keepalived.conf(5)man:genhash(1)https://keepalived.orgMain PID: 28043 (keepalived)Tasks: 2 (limit: 10840)Memory: 1.2MCPU: 22msCGroup: /system.slice/keepalived.service├─28043 /apps/keepalived/sbin/keepalived --dont-fork -D└─28044 /apps/keepalived/sbin/keepalived --dont-fork -DJan 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 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::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 1000link/ether 00:0c:29:a3:9f:06 brd ff:ff:ff:ff:ff:ffaltname enp3s0inet 172.31.0.19/21 brd 172.31.7.255 scope global noprefixroute ens160valid_lft forever preferred_lft foreverinet 172.31.0.180/32 scope global ens160:0valid_lft forever preferred_lft foreverinet6 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.180os(){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;thenrpm -q wget &> /dev/null || { ${COLOR}"安装wget工具,请稍等..."${END};yum -y install wget &> /dev/null; }fiif [ ! -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 ];thenMIRROR=mirrors.sjtug.sjtu.edu.cnif [ `grep -R "\[powertools\]" /etc/yum.repos.d/*.repo` ];thendnf config-manager --set-enabled powertoolselsecat > /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
EOFfifiif [ ${OS_ID} == "CentOS" -a ${OS_RELEASE_VERSION} == 8 ];thenMIRROR=mirrors.aliyun.comif [ `grep -R "\[powertools\]" /etc/yum.repos.d/*.repo` ];thendnf config-manager --set-enabled powertoolselsecat > /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
EOFfifiif [ ${OS_RELEASE_VERSION} == 9 ];thenyum -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/nullelif [ ${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/nullelif [ ${OS_RELEASE_VERSION} == 7 ];thenyum -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/nullelif [ ${OS_RELEASE_VERSION} == "20" -o ${OS_RELEASE_VERSION} == "22" ];thenapt 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-develseapt 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/nullfitar xf ${KEEPALIVED_FILE}KEEPALIVED_DIR=`echo ${KEEPALIVED_FILE} | sed -nr 's/^(.*[0-9]).*/\1/p'`cd ${KEEPALIVED_DIR}./configure --prefix=${KEEPALIVED_INSTALL_DIR} --disable-fwmarkmake -j $CPUS && make install[ $? -eq 0 ] && $COLOR"Keepalived编译安装成功"$END ||  { $COLOR"Keepalived编译安装失败,退出!"$END;exit; }[ -d /etc/keepalived ] || mkdir -p /etc/keepalived &> /dev/nullread -p "请输入是主服务端或备用服务端,例如(MASTER或BACKUP): " STATEread -p "请输入优先级,例如(100或80): " PRIORITYcat > /etc/keepalived/keepalived.conf <<EOF
! Configuration File for keepalivedglobal_defs {notification_email {acassen@firewall.locfailover@firewall.locsysadmin@firewall.loc}notification_email_from Alexandre.Cassen@firewall.locsmtp_server 192.168.200.1smtp_connect_timeout 30router_id LVS_DEVELvrrp_skip_check_adv_addrvrrp_strictvrrp_garp_interval 0vrrp_gna_interval 0
}vrrp_instance VI_1 {state ${STATE}interface ${NET_NAME}virtual_router_id 51priority ${PRIORITY}advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {${VIP} dev ${NET_NAME} label ${NET_NAME}:1   }
}
EOFcp ./keepalived/keepalived.service /lib/systemd/system/echo "PATH=${KEEPALIVED_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/keepalived.shsystemctl daemon-reloadsystemctl enable --now keepalived &> /dev/null systemctl is-active keepalived &> /dev/null ||  { ${COLOR}"Keepalived 启动失败,退出!"${END} ; exit; }${COLOR}"Keepalived安装完成"${END}
}main(){oscheck_fileinstall_keepalived
}main

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

DPU是什么?

问题描述&#xff1a; DPU是什么&#xff1f; 解答&#xff1a; DPU&#xff08;Data Processing Unit&#xff09;是以数据为中心构造的专用处理器&#xff0c;采用软件 定义技术路线支撑基础设施层资源虚拟化&#xff0c;支持存储、安全、服务质量管理等 基础设施层服务。…

基于x86架构的OpenHarmony应用生态挑战赛等你来战!

为了更快速推进OpenHarmony在PC领域的进一步落地&#xff0c;加快x86架构下基于OpenHarmony的应用生态的繁荣&#xff0c;为北向应用开发者提供一个更加便捷的开发环境&#xff0c;推动OpenHarmony北向应用开发者的增加&#xff0c;助力OpenHarmony在PC领域实现新的突破&#x…

buuctf_N1BOOK_粗心的小李

题目&#xff1a; 看完题目&#xff0c;git下载文件&#xff1f;然后将.git文件传到线上环境&#xff1f;&#xff08;which 会造成git泄露的安全威胁&#xff09;<这个背景抱歉我不太了解哈&#xff0c;可能后续有补充> 这里主要记录做法过程&#xff1a; 工具&#xf…

javaWeb个人学习02

会话技术 会话: 用户打开浏览器,访问web服务器的资源,会话建立,直到有一方断开连接,会话结束.在一次会话中包含多次请求和响应 会话跟踪: 一种维护浏览器状态的方法,服务器需要识别多次请求是否来自于同一个浏览器,以便在同一次会话的多次请求之间共享数据 会话跟踪方案: …

#stm学习总结 (二十八)硬件随机数实验

28.1 随机数发生器简介 STM32F407 自带了硬件随机数发生器&#xff08;RNG&#xff09;&#xff0c;RNG 处理器是一个以连续模拟噪声为基础的随机数发生器&#xff0c;在主机读数时提供一个 32 位的随机数。 28.1.1 RNG 框图 STM32F407 的随机数发生器&#xff08;RNG&#x…

React中使用useActive

1.引入 import { useActivate } from "react-activation";2.React Activation 在React中使用react-activation,其实就是类似于Vue中的keep-alive&#xff0c;实现数据的缓存&#xff1b; 源码&#xff1a; import { ReactNode, ReactNodeArray, Context, Component…

数据库的基本操作

数据库的基本操作 1创建数据库与查看数据库 创建数据库之前&#xff0c;先查看数据库&#xff1a; 然后使用命令行创建数据库&#xff1a; 再次查看数据库&#xff0c;发现多了一个数据库&#xff1a; 查看数据库基本信息&#xff1a; 2修改数据库 注意&#xff0c;修改…

Git自动忽略dll文件的问题

检查了半天发现是sourcetreee的全局忽略文件导致&#xff0c; 从里面删除dll即可。 我是干脆直接删了全局忽略&#xff0c;太恶心了&#xff0c;如下&#xff1a; #ignore thumbnails created by windows Thumbs.db #Ignore files build by Visual Studio *.exe .vsconfig .s…

使用全局事件总线实现任意组件间的通讯

本文以vue2中爷孙组件通讯为例&#xff0c;需求是点击孙组件的按钮&#xff0c;实现关闭爷组件的弹窗。 全局事件总线是通过Vue实例的事件系统来实现组件之间的通讯&#xff0c;可以方便地在任何组件中进行事件的触发和监听。 以下是使用全局事件总线实现爷孙组件通讯的步骤&a…

初阶数据结构:链表相关题目练习(补充)

目录 1. 单链表相关练习题1.1 移除链表元素1.2 反转链表1.3 链表的中间结点1.4 链表的倒数第k个结点1.5 合并两个有序链表1.6 链表分割1.7 链表的回文结构1.8 相交链表1.9 判断一个链表中是否有环1.10 寻找环状链表相遇点1.11 链表的深度拷贝 1. 单链表相关练习题 注&#xff1…

第一节:Sashulin Message Broker是什么?

一、Sashulin Message Broker简介 Sashulin Message Broker&#xff08;消息代理&#xff0c;简称SMB&#xff09;是一款可编程的消息流处理软件&#xff0c;它使应用程序、系统和服务能够相互通信并交换信息。通过消息传递和转换&#xff0c;实现不同平台和不同语言编写的服务…

登录页设计新选择:毛玻璃和新拟态风格,非2.5D和插画风

登录页给潜在用户传递了产品的品牌调性&#xff0c;是非常重要的一类页面&#xff0c;之前2.5D和插画风格的登录页流行一时&#xff0c;不过这阵风好像过去了&#xff0c;新的风格开始涌现了。 一、越来越流行的毛玻璃设计风格 毛玻璃风格是指将背景模糊处理&#xff0c;使得…

DOM 获取父子节点

DOM 是以树状结构排列的&#xff0c;所以父子关系是相对的&#xff0c;当li为我们的目标节点的时候&#xff0c;ul为其父节点&#xff0c;其他li为它的兄弟节点&#xff0c;li里面包含的标签为子节点&#xff0c;以此类推。 那我们如何找父节点&#xff1f; 元素.parentNode&am…

长江路一号桥的安全监测革新

位于无锡新区的长江路一号桥&#xff0c;自1997年落成以来&#xff0c;一直是多功能的市政要道。大桥北侧连接供气管道&#xff0c;右侧则是城市供水管道&#xff0c;而桥底则设有蓝藻环保监测点。这意味着一旦此桥出现问题&#xff0c;其影响远超交通堵塞的层面。近年来&#…

密码学及其应用(应用篇15)——0/1背包问题

1 问题背景 背包问题是一个经典的优化问题&#xff0c;在计算机科学和运筹学中有着广泛的应用。具体到你提到的这个问题&#xff0c;它是背包问题中的一个特例&#xff0c;通常被称为0/1背包问题。这里&#xff0c;我们有一系列的正整数 &#xff0c;以及一个正整数&#xff0c…

推荐一个 Obsidian 的 ChatGPT 插件

源码地址&#xff1a;https://github.com/nhaouari/obsidian-textgenerator-plugin Text Generator 是目前我使用过的最好的 Obsidian 中的 ChatGPT 功能插件。它旨在智能生成内容&#xff0c;以便轻松记笔记。它不仅可以在 Obsidian 中直接使用 ChatGPT&#xff0c;还提供了优…

《大模型时代-ChatGPT开启通用人工智能浪潮》精华摘抄

原书很长&#xff0c;有19.3w字&#xff0c;本文尝试浓缩一下其中的精华。 知识点 GPT相关 谷歌发布LaMDA、BERT和PaLM-E&#xff0c;PaLM 2 Facebook的母公司Meta推出LLaMA&#xff0c;并在博客上免费公开LLM&#xff1a;OPT-175B。 在GPT中&#xff0c;P代表经过预训练(…

Python入门到精通(九)——Python数据可视化

Python数据可视化 一、JSON数据格式 1、定义 2、python数据和JSON数据转换 二、pyecharts 三、折线图 四、地图 五、动态柱状图 一、JSON数据格式 1、定义 JSON是一种轻量级的数据交互格式。可以按照JSON指定的格式去组织和封装数据JSON本质上是一个带有特定格式的字符…

数仓项目6.0(二)数仓

中间的几步意义就在于&#xff0c;缓存中间处理数据样式&#xff0c;避免重复计算浪费算力 分层 ODS&#xff08;Operate Data Store&#xff09; Spark计算过程中&#xff0c;存在shuffle的操作&#xff0c;而shuffle会将计算过程一分为二&#xff0c;前一阶段不执行完&…

mongo之常用数据库操作

目录 一、准备环境 二、日常记录及执行示范 连接数据库查询版本查询表总数模糊查询(使用正则)查询文档中数据条数排序大于等于查询有哪些库时间查询不在条件内的查询复制数据更新字段名称删除数据库 四、高阶查询 五、备份迁移数据库 总结 一、准备环境 借鉴&#xff1a;…