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.mzph.cn/news/709580.shtml

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

相关文章

mongo之常用数据库操作

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

模型选择与评估

&#x1f6a9; 机器学习的一般流程包括&#xff1a;数据集的准备与预处理、搭建模型、模型训练、模型评估与应用。 在现实任务中&#xff0c;我们往往有多种学习算法可供选择&#xff0c;甚至对同一个学习算法&#xff0c;当使用不同的参数配置时&#xff0c;也会产生不同的模型…

模块整理!YOLOv9中的“Silence”、“RepNCSPELAN4”、“ADown”、“CBLinear”创新模块汇总!

代码链接&#xff1a;https://github.com/WongKinYiu/yolov9/tree/main 论文链接&#xff1a;YOLOv9: Learning What You Want to Learn Using Programmable Gradient Information 大量文字及图片来袭&#xff01; 本文整理了YOLOv9中的创新模块&#xff0c;附代码和结构图&a…

【Java程序设计】【C00323】基于Springboot的高校科研信息管理系统(有论文)

基于Springboot的高校科研信息管理系统&#xff08;有论文&#xff09; 项目简介项目获取开发环境项目技术运行截图 项目简介 这是一个基于Springboot的高校科研信息管理系统&#xff0c;本系统有管理员、学校管理员、科研人员三种角色&#xff1b; 管理员&#xff1a;首页、个…

JavaWeb之 创建 Web项目,使用Tomcat 部署项目,使用 Maven 构建Web项目(一万八千字详解)

目录 前言3.1 Tomcat 简介3.1.1 什么是 Web服务器3.1.2 Tomcat 是什么3.1.3 小结 3.2 Tomcat 的基本使用3.2.1 下载 Tomcat3.2.2 安装 Tomcat3.2.3 卸载 Tomcat3.2.4 启动 Tomcat3.2.5 关闭 Tomcat3.2.6 配置 Tomcat3.2.7 在 Tomcat 中部署 Web项目 3.3 在 IDEA 中创建 Web 项目…

(C语言)二分查找

在⼀个升序的数组中查找指定的数字n&#xff0c;很容易想到的⽅法就是遍历数组&#xff0c;但是这种⽅法效率⽐较低。⽐如我买了⼀双鞋&#xff0c;你好奇问我多少钱&#xff0c;我说不超过300元。你还是好奇&#xff0c;你想知道到底多少&#xff0c;我就让你猜&#xff0c;你…

【电路笔记】-RC网络-RC积分器

RC积分器 文章目录 RC积分器1、概述2、RC积分器3、电容电压4、单脉冲 RC 积分器5、RC积分器示例6、RC 积分器作为正弦波发生器7、总结RC 积分器是一个串联的 RC 网络,可产生与积分的数学过程相对应的输出信号。 1、概述 对于无源 RC 积分器电路,输入连接到电阻,而输出电压取…

GCN 翻译 - 1

ABSTRACT 我们提出了一种可扩展的在以图结构为基础的数据上的半监督学习&#xff0c;这种方法直接作用在图数据上&#xff0c;可以看做是卷积神经网络的变种。我们选择了图谱理论里面的一阶近似作为我们的卷积结构。我们的模型能够随着图的规模线性伸缩&#xff0c;并且隐藏层…

【生态适配】亚信安慧AntDB数据库与FT-2000+/64处理器完成兼容互认

日前&#xff0c;亚信安慧AntDB数据库完成了与FT-2000/64处理器的兼容互认。经湖南亚信安慧科技有限公司&#xff08;简称“亚信安慧”&#xff09;与飞腾信息技术有限公司&#xff08;简称“飞腾公司”&#xff09;的严格测试&#xff0c;亚信安慧AntDB数据库V6.2在FT-2000/64…

【前端素材】推荐优质在线家具电商网页Hurst平台模板(附源码)

一、需求分析 1、系统定义 家具电商平台是指专门销售家具产品的在线电子商务平台。这些平台专注于家具类商品的销售和服务&#xff0c;为消费者提供方便快捷的购买体验。 2、功能需求 在线家具商城平台是指通过互联网提供家具购买服务的电子商务平台。这类平台为消费者和家…

基于ESP32的MicroPython项目量产烧写指南

背景 前段时间用MicroPython开发了一个项目&#xff0c;硬件是ESP32-C3&#xff0c;目前准备量产&#xff0c;我需要提供固件以供加工厂批量烧录&#xff0c;需要把我有程序的板子里的程序读出来&#xff0c;然后下到别的板子上&#xff0c;以下做这件事情的过程记录。 1.固件…

3_相机模型

相机标定对于联系相机测量和真实三维世界测量也很重要。它的重要性在于场景不仅仅是三维的&#xff0c;也是物理单位度量的空间。因此&#xff0c;确定相机的自然单位(像素)与物理单位(如mm)的关系是三维场景重构的重要部分。相机标定的过程既给出相机的几何模型又给出透镜的畸…

电感器在电路中的作用

同学们大家好&#xff0c;今天我们继续学习杨欣的《电子设计从零开始》&#xff0c;这本书从基本原理出发&#xff0c;知识点遍及无线电通讯、仪器设计、三极管电路、集成电路、传感器、数字电路基础、单片机及应用实例&#xff0c;可以说是全面系统地介绍了电子设计所需的知识…

pause、alarm、kill——进程——day13

今天主要讲线程中信号的三个函数 1.pause 1.pauseint pause(void); 功能:让进程睡眠,直到接收到信号(捕捉)才能继续向下执行eg&#xff1a; #include "head.h"void handler(int signo) {return; }int main(void) {signal(SIGINT,handler);printf("pause up!\…

学习大语言模型(LLM),从这里开始

在见识了ChatGPT的各种强大能力后&#xff0c;不少 NLP一线从业人员很自然地想到&#xff0c;以后开发者只要借助 ChatGPT&#xff0c;就可以做到现在大部分NLP工程师在做的事&#xff0c;比如文本分类、实体抽取、文本推理等。甚至随着大语言模型&#xff08;largelanguagemod…

Keepalived 双机热备基础知识

7.1 Keepalived 双机热备基础知识 Keepalived起初是专门针对LVS设计的一款强大的辅助工具&#xff0c;主要用来提供故障切换(Failover) 和健康检查査(Health Checking)功能一一判断LVS 负载调度器、节点服务器的可用性&#xff0c;及时隔离并替 换为新的服务器&#xff0c;当故…

Container killed on request. Exit code is 143

Bug信息 WARN YarnAllocator: Container marked as failed: container_e33_1480922439133_0845_02_000002 on host: hdp4. Exit status: 143. Diagnostics: Container killed on request. Exit code is 143 Container exited with a non-zero exit code 143 Killed by externa…

day03_登录注销(前端接入登录,异常处理, 图片验证码,获取用户信息接口,退出功能)

文章目录 1. 前端接入登录1.1 修改前端代码1.2 跨域请求1.2.1 跨域请求简介1.2.2 COSR概述CORS简介CORS原理 1.2.3 CORS解决跨域 2. 异常处理2.1 提示空消息分析2.2 系统异常分类2.3 异常处理2.2.1 方案一2.2.2 方案二 3. 图片验证码3.1 图片验证码意义3.2 实现思路3.3 后端接口…

java找工作之JavaWeb(一)

JavaWeb 一个web应用有多部份组成&#xff08;静态web&#xff0c;动态web&#xff09; html&#xff0c;css&#xff0c;jsjsp&#xff0c;servletjava程序jar包配置文件(Properties) web应用程序编写完毕后&#xff0c;若想提供给外界访问&#xff0c;需要一个服务器来统一…

【IC验证】数据类型

一、思维导图 二、代码 &#xff08;1&#xff09;字符串 字符串的结尾不带空标识符null&#xff0c;\0。是动态存储方式&#xff0c;因此不用担心存储空间被用完。 编辑.SV文件使用 gvim 文件名 运行仿真使用 vcs -sverilog -full64 string_type.sv 和./simv命令如果是字…