一、演示环境说明
操作系统:ubuntu 22.04.3 LTS
演示服务器IP地址
主机:192.168.0.19
备机:192.168.0.56
浮动IP:192.168.0.120
注:以下操作均需root权限
安装keepalived
apt install keepalived
配置keepalived
# 主机keepalived配置cd /etc/keepalived cat keepalived.conf ! Configuration File for keepalived global_defs { router_id balance01 #xx主备id enable_script_security script_user root } #加入周期性检测nginx服务脚本的相关配置vrrp_script check_nginx { script "/etc/keepalived/check_nginx.sh"#心跳执行的脚本,检测nginx是否启动 interval 2#(检测脚本执行的间隔,单位是秒)} vrrp_instance VI_1 { state BACKUP interface eth0 #网卡名称 virtual_router_id 51 priority 99#优先级,主不改,备改成比100小就行 advert_int 1 authentication { auth_type PASS auth_pass NgLMwBmE } unicast_src_ip 192.168.0.19 #这里是主服务器私网ip unicast_peer { 192.168.0.56 #备服务器的私网ip,如果有多个,可以换行添加(对端ip,比如主的这里写备的内网ip) } virtual_ipaddress { 192.168.0.120 label eth0:0 } #添加跟踪(执行脚本) track_script { check_nginx } } # 备机keepalived配置! Configuration File for keepalived global_defs { router_id balance01 #xx主备id enable_script_security script_user root } #加入周期性检测nginx服务脚本的相关配置vrrp_script check_nginx{ script "/etc/keepalived/check_nginx.sh"#心跳执行的脚本,检测nginx是否启动 interval 2#(检测脚本执行的间隔,单位是秒)} vrrp_instance VI_1 { state MASTER interface eth0 #网卡名称 virtual_router_id 51 priority 100#优先级,主不改,备改成比100小就行 advert_int 1 authentication { auth_type PASS auth_pass NgLMwBmE } unicast_src_ip 192.168.0.56 #这里是主服务器私网ip unicast_peer { 192.168.0.19 #备服务器的私网ip,如果有多个,可以换行添加(对端ip,比如主的这里写备的内网ip) } virtual_ipaddress { 192.168.0.120 label eth0:0 } 添加跟踪(执行脚本) track_script{ check_nginx } } # chech_nginx.sh脚本#检查nginx进程是否存在count=$(ps -C nginx --no-heading | wc -l)#进程数等于0的时候if [ "${count}"="0" ]; then#尝试启动一次nginx,停止2秒后再次检测 /home/ops/server/nginx/sbin/nginx sleep2count=$(ps -C nginx --no-heading | wc -l)if [ "${count}"="0" ]; then#如果启动没成功,就杀掉keepalive触发主备切换 systemctl stop keepalived fifi
启动及检查
systemctl enable keepalived systemctl start keepalived
分别在主、备机上启动keepalived,然后用ifconfig -a命令查看,此时主机的eth0:0接口会绑定浮动IP
ifconfig -aeth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.0.56 netmask 255.255.255.0 broadcast 192.168.0.255 inet6 fe80::f816:3eff:fe76:ce06 prefixlen 64 scopeid 0x20<link> ether fa:16:3e:76:ce:06 txqueuelen 1000 (Ethernet) RX packets 423293 bytes 233312508 (233.3 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 437023 bytes 331280752 (331.2 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0eth0:0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.0.120 netmask 255.255.255.255 broadcast 0.0.0.0 ether fa:16:3e:76:ce:06 txqueuelen 1000 (Ethernet) lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10<host> loop txqueuelen 1000 (Local Loopback) RX packets 78258 bytes 8896394 (8.8 MB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 78258 bytes 8896394 (8.8 MB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
主机关闭keepalived,从机会接管浮动IP,说明keepalived生效。