1、实验环境
一台Nginx主节点 192.168.1.101
一台Nginx备节点 192.168.1.102
二台tomcat服务器 192.168.1.103;192.168.1.104
2、安装keepalived
主备Nginx上分别安装keepalived
yum -y install keepalived
#编写主备nginx检查脚本
vi /etc/keepalived/nginx_check.sh
#!/bin/bash
CHK_PORT=$1
if [ -n "$CHK_PORT" ];then
PORT_PROCESS=`ss -lnt|grep $CHK_PORT|wc -l`
if [ $PORT_PROCESS -eq 0 ];then
echo "Port $CHK_PORT Is Not Used,End."
exit 1
fi
else
echo "Check Port Cant Be Empty!"
fi
#授权
chmod 755 nginx_check.sh
3、主节点(Master)配置
vi /etc/keepalived/keepalived.conf
#配置内容如下
! Configuration File for keepalived
global_defs {
router_id localhost
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh 80"
interval 2
weight -20
}
vrrp_instance VI_1 {
state MASTER
interface ens33 #本地网卡名称
virtual_router_id 50
mcast_src_ip 192.168.1.101 #本机IP
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.1.200 #配置同网段空闲地址,做虚拟IP
}
}
4、备节点(Backup)配置
vi /etc/keepalived/keepalived.conf
#配置内容如下
! Configuration File for keepalived
global_defs {
router_id localhost
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh 80"
interval 2
weight -20
}
vrrp_instance VI_1 {
state BACKUP
interface ens33 #本地网卡名称
virtual_router_id 50
mcast_src_ip 192.168.1.102 #本机IP
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.1.200 #配置同网段空闲地址,做虚拟IP
}
}
5、配置主备nginx轮询负载
vi /usr/local/nginx/conf/nginx.conf
#配置内容如下
upstream web {
server 192.168.1.104:8080;
server 192.168.1.103:8080;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
#root html;
proxy_pass http://web;
index index.html index.htm;
}
}
6、启动分别启动主备服务器Nginx和keepalived
systemctl start nginx
systemctl start keepalived
7、停止主服务器nginx服务测试
systemctl stop nginx
8、访问虚拟IP依然可以进行负载均衡