keepalived配置nginx高可用

名词解释:

高可用: High Availability (HA)
负载均衡: Load Balance (LB)
服务器负载均衡: Server Load Balancing (SLB)

区别: 高可用性:顾名思义,尽可能采取措施减少系统服务中断时间,进而提高业务程序持续对外提供服务的能力。 负载均衡:将高并发的请求数据分发到不同的集群结点,尽量平衡系统所有资源的压力,从而提升整个集群对于请求的处理能力

环境说明:

主机A 192.168.128.8 nginx + keepalived
主机B 192.168.128.9 nginx + keepalived

通过keepalived配置nginx高可用, keepalived配置nginx对外虚拟地址为 192.168.128.10

软件安装

主机A: yum install keepalived nginx
主机B: yum install keepalived nginx

主机A配置

  1. keepalived 配置

/etc/keepalived/keepalived.conf

vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh" # 检测nginx状态的脚本路径
interval 2 # 检测时间间隔2s
weight -20 # 如果脚本的条件成立,权重-20
}

vrrp_instance VI_1 {
state MASTER # 服务状态;MASTER(工作状态)BACKUP(备用状态)
interface ens33 # VIP绑定网卡
virtual_router_id 51 # 虚拟路由ID,主、备节点必须一致
mcast_src_ip 192.168.128.8 # 本机IP
nopreempt # 优先级高的设置,解决异常回复后再次抢占的问题
priority 90 # 优先级;取值范围:0~254;MASTER > BACKUP
advert_int 1 # 组播信息发送间隔,主、备节点必须一致,默认1s
authentication { # 验证信息;主、备节点必须一致
auth_type PASS # VRRP验证类型,PASS、AH两种
auth_pass 1111 # VRRP验证密码,在同一个vrrp_instance下,主、从必须使用相同的密码才能正常通信
}
track_script { # 将track_script块加入instance配置块
chk_nginx # 执行Nginx监控的服务
}
virtual_ipaddress { #虚拟IP池,主、备节点必须一致,可以定义多个VIP
192.168.128.10 # 虚拟IP
}
}
  1. nginx 脚本配置

vim /etc/keepalived/nginx_check.sh
chmod +x /etc/keepalived/nginx_check.sh

#!/bin/bash
if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ];then
#echo 1
systemctl start nginx
sleep 5

if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ];then
systemctl stop keepalived
#echo 2
fi
fi

主机B配置

  1. keepalived 配置
    和主机A的配置除了本机ip, 优先级不同, 其他均相同配置

/etc/keepalived/keepalived.conf

vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh" # 检测nginx状态的脚本路径
interval 2 # 检测时间间隔2s
weight -20 # 如果脚本的条件成立,权重-20
}

vrrp_instance VI_1 {
state MASTER # 服务状态;MASTER(工作状态)BACKUP(备用状态)
interface ens33 # VIP绑定网卡
virtual_router_id 51 # 虚拟路由ID,主、备节点必须一致
mcast_src_ip 192.168.128.9 # 本机IP
nopreempt # 优先级高的设置,解决异常回复后再次抢占的问题
priority 100 # 优先级;取值范围:0~254;MASTER > BACKUP
advert_int 1 # 组播信息发送间隔,主、备节点必须一致,默认1s
authentication { # 验证信息;主、备节点必须一致
auth_type PASS # VRRP验证类型,PASS、AH两种
auth_pass 1111 # VRRP验证密码,在同一个vrrp_instance下,主、从必须使用相同的密码才能正常通信
}
track_script { # 将track_script块加入instance配置块
chk_nginx # 执行Nginx监控的服务
}
virtual_ipaddress { #虚拟IP池,主、备节点必须一致,可以定义多个VIP
192.168.128.10 # 虚拟IP
}
}
  1. nginx 脚本配置
    和主机A的配置一样哦

vim /etc/keepalived/nginx_check.sh
chmod +x /etc/keepalived/nginx_check.sh

#!/bin/bash
if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ];then
#echo 1
systemctl start nginx
sleep 5

if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ];then
systemctl stop keepalived
#echo 2
fi
fi

配置启动

主机A和主机B配置 keppalived 和 nginx 自启
systemctl enable nginx
systemctl enable keepalived
systemctl start nginx
systemctl start nginx

这个时候A和B的nginx就是一个主从关系. 只要其中一个nginx正常就可以通过keepalived虚拟的192.168.128.10 正常访问到nginx