keepalived + nginx实现高可用web集群
集群架构图
- 首先准备五台centos7系统的虚拟机
- 每台机器上安装好nginx
一键编译安装nginx脚本 - 修改两台负载均衡nginx的配置文件
http {
...
upstream my_nginx_lb {
server 192.168.44.132;
server 192.168.44.133;
server 192.168.44.134;
...
}
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
proxy_pass http://my_nginx_lb;
}
...
}
- 分别再两台机器上安装keepalived
yum install keepalived -y
- 修改配置文件
master主机上
global_defs {
router_id nginx_keepalived
#vrrp_skip_check_adv_addr
#vrrp_strict
#vrrp_iptables
script_user root //执行脚本的用户
enable_script_security
}
vrrp_script check_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 66
priority 100
advert_int 2
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.44.100/24 ens33
}
track_script {
check_nginx
}
}
backup主机上
global_defs {
router_id nginx_keepalived2
script_user root
enable_script_security
}
vrrp_script check_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
}
vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 66
priority 80
advert_int 2
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.44.100/24 ens33
}
track_script {
check_nginx
}
}
脚本/etc/keepalived/check_nginx.sh,检查maste 主机上nginx是否down机,如果down机停止keepalived,vip飘逸至backup主机
#! /usr/bin/bash
check_result=`ps -C nginx --no-header|wc -l`
if [ $check_result -eq 0 ];then
killall keepalived
fi
- 查看master负载均衡器上的ip,并访问虚拟ip:192.168.44.100
- 关闭master上的nginx,继续访问vip
发现仍可以继续访问
查看backup主机ip,发现vip漂移至backup
至此完成双主高可用web集群