0x00 实验环境
本次实验所用环境如下:
虚拟机:VirtualBox 6.1 创建的两台CentOS7虚拟机
OS:CentOS Linux release 7.7.1908 (Core)
Nginx :nginx version: nginx/1.20.1
Keepalived:Keepalived v1.3.5 (03/19,2017), git commit v1.3.5-6-g6fa32f2
限制:此方法要求服务器的hostname必须不能包含“nginx”字符串,否则可能会影响到监控脚本的执行(未验证)。
0x01 禁用SELinux:
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config setenforce 0
0x02 安装epel:
rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org yum install https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm
0x03 安装keepalived:
yum install keepalived -y
运行日志位置:
/var/log/messages
0x04 修改配置文件:
master节点配置文件内容(vim /etc/keepalived/keepalived.conf):
! Configuration File for keepalived global_defs { router_id LVS_nginx1 } vrrp_script trackngx { script "/root/chk_nginx_pid.sh" interval 5 } vrrp_instance VI_1 { state MASTER interface enp0s3 virtual_router_id 51 priority 150 advert_int 1 authentication { auth_type PASS auth_pass 51yunjiance.com } virtual_ipaddress { 172.171.19.238 } track_script { trackngx } }
backup节点配置文件内容(vim /etc/keepalived/keepalived.conf):
! Configuration File for keepalived global_defs { router_id LVS_nginx2 } vrrp_script trackngx { script "/root/chk_nginx_pid.sh" interval 5 } vrrp_instance VI_1 { state BACKUP interface enp0s3 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 51yunjiance.com } virtual_ipaddress { 172.171.19.238 } track_script { trackngx } }
0x05 添加监控nginx进程脚本(两台机器都要添加):
该脚本会尝试先启动nginx,如果启动失败,则停止keepalived服务,保证节点顺利下线。
注意,此脚本会自动启动nginx,可能对运维时产生一定的影响。
vim /root/chk_nginx_pid.sh
#!/bin/sh nginxpid=$(ps -C nginx --no-header | wc -l) if [ $nginxpid -eq 0 ] then systemctl start nginx sleep 3 nginxpid=$(ps -C nginx --no-header | wc -l) if [ $nginxpid -eq 0 ];then systemctl stop keepalived fi fi
修改为可执行文件:
chmod +x chk_nginx_pid.sh
0x06 设置自启动并启动keepalived
keepalived随系统自启动:
systemctl enable keepalived
启动keepalived:
systemctl start keepalived
0x07 验证
手动停止nginx后会自动拉起nginx,关闭其中一台主机后,另外一台主机稍后会自动接管虚拟IP。