虚拟IP搭建主从模式
服务器 | 172.24.64.66,172.24.64.67 |
---|---|
虚拟IP、VIP | 172.24.64.71 |
Nginx版本 | 1.26.0 |
Keepalived版本 | 2.2.7 |
Keepalived编译安装
准备工作
-
官网下载:https://www.keepalived.org/download.html
-
依赖安装:在开始安装Keepalived之前,您需要安装一些必要的依赖库。这些库可能包括gcc、openssl-devel、libnfnetlink-devel等。您可以使用以下命令来安装这些依赖(以CentOS为例):
yum -y install gcc openssl-devel libnfnetlink-devel
下载并解压Keepalived源码
tar -zxvf /usr/local/src/keepalived-2.2.7.tar.gz -C /usr/local/src/
编译安装
cd /usr/local/src/keepalived-2.2.7/
#执行配置脚本:执行configure脚本来配置编译参数。
#您可以使用以下命令,其中--prefix参数指定了Keepalived的安装目录
#其中--sysconf参数指定了Keepalived配置文件路径
./configure --prefix=/usr/local/keepalived --sysconf=/etc/keepalived
#编译安装
make && make install
#启动,会因找不到配置文件报错
/usr/local/keepalived/sbin/keepalived
配置Keepalived
Keepalived启动时默认读取配置路径
#查看
/usr/local/keepalived/sbin/keepalived --help
-f, --use-file=FILE Use the specified configuration file
default '/usr/local/etc/keepalived/keepalived.conf'
or '/etc/keepalived/keepalived.conf'
复制配置文件
mkdir -p /etc/keepalived/
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/
编辑配置文件
vi /etc/keepalived/keepalived.conf
keepalived.conf
! Configuration File for keepalived
global_defs {
router_id LVS_1
}
vrrp_script check_nginx_alive {
script "/etc/keepalived/chk_nginx.sh"
interval 2 #每隔两秒钟运行脚本检测
weight 10 #脚本运行成功,升级权重+10
}
vrrp_instance VI_1 {
# 表示状态是MASTER主机还是备用机BACKUP
state BACKUP
# 该实例绑定的网卡
interface ens192
# 保证主备节点一致即可
virtual_router_id 51
# 权重,master权重一般高于backup,如果有多个,那就是选举,谁的权重高,谁就当选
priority 100
# 主备之间同步检查时间间隔,单位秒
advert_int 1
# 认证权限密码,防止非法节点进入 主从保持一致
authentication {
auth_type PASS
auth_pass 1111
}
# 虚拟出来的ip,可以有多个(vip)
virtual_ipaddress {
172.24.64.71
}
# Nginx服务检查脚本,对应上面的vrrp_script check_nginx_alive
track_script{
check_nginx_alive
}
}
chk_nginx.sh Nginx 检测脚本
#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
#Nginx启动路径
/usr/local/nginx-1.26.0/sbin/nginx
sleep 2
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
killall keepalived
fi
fi
- interface 对应的是服务器的网卡配置文件 ip addr可以查看
- 启动前也查看下ip信息,观察变化
此为启动成功后截图,网卡下多出虚拟IP
设置开机自启
启动
/usr/local/keepalived/sbin/keepalived
#指定配置文件启动
/usr/local/keepalived/sbin/keepalived -f /etc/keepalived/keepalived.conf
#查看是否启动成功
ps -ef | grep keepalived
ip addr