Keepalived + Nginx 高可用集群 (主从模式)
集群架构图
搭建
所需环境
HOSTNAME | IP | 说明 |
---|---|---|
LB-01 | 192.168.145.135 | Keepalived 主服务器(Nginx 主负载均衡器) |
LB-02 | 192.168.145.136 | Keepalived 备服务器(Nginx 备负载均衡器) |
WEB-01 | 192.168.145.137 | Web 服务器节点1 |
WEB-02 | 192.168.145.138 | Web 服务器节点2 |
安装 Nginx
在 LB-01,LB-02 分别安装 Nginx
Linux 安装 Nginx
安装 Tomcat
在 WEB01, WEB02 分别安装 Tomcat
Linux 安装 Tomcat
配置 Nginx LB-01
upstream backserver {server 192.168.145.137:8080;server 192.168.145.138:8080;}server {listen 80;server_name LB-01;location / {proxy_pass http://backserver;}}
配置 Nginx LB-02
upstream backserver {server 192.168.145.137:8080;server 192.168.145.138:8080;}server {listen 80;server_name LB-02;location / {proxy_pass http://backserver;}}
安装 Keepalived
在两台 Nginx 服务器都安装 Keepalived
yum install keepalived -y
配置主 keepalived
配置文件在 /etc/keepalived
! Configuration File for keepalivedglobal_defs {notification_email {acassen@firewall.locfailover@firewall.locsysadmin@firewall.loc}notification_email_from Alexandre.Cassen@firewall.locsmtp_server 192.168.145.135smtp_connect_timeout 30router_id LVS_DEVEL # 通过这个名字能访问到主机,需要修改 /etc/hosts 文件添加 127.0.0.1 LVS_DEVEL
}vrrp_script chk_http_port {script "/usr/local/nginx/nginx_check.sh" # 脚本文件位置,监听 Nginx 状态interval 2 # 检测脚本执行的间隔weight 2}vrrp_instance VI_1 {state MASTER # 备份服务器上将 MASTER 改为 BACKUPinterface ens33 # 网卡,通过 ifconfig 命令查看网卡名称virtual_router_id 51 # 主、备机的 virtual_router_id 须相同priority 100 # 主、备机取不同的优先级,主机值较大,备机值较小advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.145.110 # VRRP H 虚拟地址,网段要一致}
}
配置脚本文件,监听 nginx 状态
vi /usr/local/nginx/nginx_check.sh
#!/bin/bash
A=`ps -C nginx ¨Cno-header |wc -l`
if [ $A -eq 0 ];then/usr/local/nginx/sbin/nginxsleep 2if [ `ps -C nginx --no-header |wc -l` -eq 0 ];thenkillall keepalivedfi
fi
配置从 Keepalived
! Configuration File for keepalivedglobal_defs {notification_email {acassen@firewall.locfailover@firewall.locsysadmin@firewall.loc}notification_email_from Alexandre.Cassen@firewall.locsmtp_server 192.168.145.142smtp_connect_timeout 30router_id LVS_DEVEL # 通过这个名字能访问到主机,需要修改 /etc/hosts 文件添加 127.0.0.1 LVS_DEVEL
}vrrp_script chk_http_port {script "/usr/local/nginx/nginx_check.sh" # 脚本文件位置interval 2 # 检测脚本执行的间隔weight 2}vrrp_instance VI_1 {state BACKUP # 备份服务器上将 MASTER 改为 BACKUPinterface ens33 # 网卡virtual_router_id 51 # 主、备机的 virtual_router_id 须相同priority 90 # 主、备机取不同的优先级,主机值较大,备机值较小advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.145.110 # VRRP H 虚拟地址}
}
配置脚本文件,监听 nginx 状态
vi /usr/local/nginx/nginx_check.sh
#!/bin/bash
A=`ps -C nginx ¨Cno-header |wc -l`
if [ $A -eq 0 ];then/usr/local/nginx/sbin/nginxsleep 2if [ `ps -C nginx --no-header |wc -l` -eq 0 ];thenkillall keepalivedfi
fi
启动 Nginx
./nginx
启动 Keepalived
systemctl start keepalived.service
测试
访问配置的虚拟IP:192.168.145.110
访问成功,这时关闭主服务器的 nginx 和 keepalived
./nginx -s stop
systemctl stop keepalived.service
再次访问虚拟IP:192.168.145.110,还是能访问成功