环境准备
-
两个linux虚拟机并各自开启nginx
-
虚拟机中安装keepalived
安装好的keepalived会在/etc下,并生成相关配置
监测脚本
nginx_check.sh
#!/bin/bash
A=`ps -C nginx -no-header | wc -1`
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -1` -eq 0 ];then
killall keepalived
fi
fi
放置位置
/usr/local/src
启动keepalived服务实例
在两台虚拟机上都要启动该服务
systemctl start keepalived.service
查看启动状态
ps -ef | grep keepalived
修改主nginx节点配置
虚拟地址可以设置多个,每行一个
必须和nginx服务器处于同一网段
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.79.132
smtp_connect_timeout 30
router_id RD1 # 路由id,必须唯一,可以在本机的/etc/hosts文件中设置
}
vrrp_script chk_http_port{
script "/usr/local/src/nginx_check.sh" # 检测脚本
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER # 指定keepalived的角色,master为主,backup为备
interface ens33 # 当前进行vrrp通讯的网络接口卡(当前centos的网卡)
virtual_router_id 51 # 虚拟路由编号,主从要一致!
priority 100 #权重,主服务器要高于从服务器,数值越大获得请求的优先级越高
advert_int 1 #检查间隔,默认为1s(vrrp组播周期秒数)
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.79.138 #可以设置多个,每行一个,注意必须和nginx服务器处于同一网段
}
}
修改从节点配置
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.79.133
smtp_connect_timeout 30
router_id RD2
}
vrrp_script chk_http_port{
script "/usr/local/src/nginx_check.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 51
priority 99
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.79.138
}
}
查看绑定状态
ip a
测试
重启nginx
要先cd 到nginx的sbin目录下
./nginx -s stop
./nginx
重启keepalived服务
systemctl restart keepalived.service
查看keepalived服务日志
tail -f /var/log/messages
停掉nginx的主节点
虚拟网络IP依然可以访问