IP | 备注 |
---|---|
192.168.174.128 | 主,关闭防火墙 、安全规则 |
192.168.174.129 | 从,关闭防火墙、安全规则 |
1.部署keepalived
2.配置keepalived日志
3.配置自定义监测nginx服务脚本
以下操作都需要在两台机器上操作
yum安装keepalived、ipvsadm、nginx
#yum -y install epel-release //centos7自带yum源没有nginx,需要安装扩展yum源
#yum install keepalived ipvsadm nginx
配置/etc/keepalived/keepalived文件,两者只有两个地方不同,STATE(主从),priority(权重)高的为主,注意不要有多余的空格
#vi /etc/keepalived/keepalived
global_defs {
notification_email {
root@localhost
}
notification_email_from root@aminglinux.com
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/usr/local/sbin/check_ng.sh" //检测nginx服务脚本位置
interval 3
}
vrrp_instance VI_1 {
state MASTER //从为BACKUP
interface eno16777736 //网卡名
virtual_router_id 79
priority 100 //从节点要低于这个值
advert_int 1
authentication {
auth_type PASS
auth_pass admin
}
virtual_ipaddress {
192.168.174.100
}
track_script {
chk_nginx
}
}
配置日志位置,/erc/rsyslog.conf在local7下面加一条local0 例如local0.* /var/log/keepalived.log 之后重启rsyslog服务,配置/etc/sysconfig/keepalived ‘-D -d -S 0’ 重启keepalived服务即配置成功
重启keepalived后主节点多出了vip
配置监控nginx脚本,存放位置看keppalived配置文件内vrrp_script chk_nginx函数的路径,编辑完后赋予x权限
#vi /usr/local/sbin/check_ng.sh
#!/bin/bash
#时间变量,用于记录日志
d=`date --date today +%Y%m%d_%H:%M:%S`
#计算nginx进程数量
n=`ps -C nginx --no-heading|wc -l`
#如果进程为0,则启动nginx,并且再次检测nginx进程数量,
#如果还为0,说明nginx无法启动,此时需要关闭keepalived
if [ $n -eq 0 ]; then
systemctl start nginx
n2=`ps -C nginx --no-heading|wc -l`
if [ $n2 -eq 0 ]; then
echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log
systemctl stop keepalived
fi
fi
#chmod +x /usr/local/sbin/check_ng.sh
测试
#systemctl stop nginx //主节点关闭nginx服务
# ip a //vip从主节点移动到从节点
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eno16777736: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:d0:1b:1e brd ff:ff:ff:ff:ff:ff
inet 192.168.174.129/24 brd 192.168.174.255 scope global eno16777736
valid_lft forever preferred_lft forever
inet 192.168.174.100/32 scope global eno16777736
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fed0:1b1e/64 scope link
valid_lft forever preferred_lft forever