负载均衡(DR)
1.实验环境
- 准备三台机器
- 网络使用NAT模式
- DR模式要求DIP与RIP必须在同一个王段及广播域
- 关闭防火墙与selinux
2.分发器配置
#安装分发器并启动
[root@localhost ~]# yum -y install ipvsadm
[root@localhost ~]# systemctl start ipvsadm
#上一步报错,需要给他创建一个文件
#配置VIP
[root@localhost ~]# ip addr add dev ens33 192.168.222.200/32
#如果IP添加错误删除如下
[root@localhost ~]# ip addr del dev ens33 192.168.222.200/32
#定义LVS分发策略
[root@localhost ~]# ipvsadm -A -t 192.168.222.200:80 -s rr
[root@localhost ~]# ipvsadm -a -t 192.168.222.200:80 -r 192.168.222.131:80 -g
[root@localhost ~]# ipvsadm -a -t 192.168.222.200:80 -r 192.168.222.132:80 -g
3.RS配置
#安装nginx
[root@localhost ~]# yum -y install nginx
#更改TCP连接的保存时间
[root@localhost ~]# vim /etc/nginx/nginx.conf +27
tcp_nodelay on;
keepalive_timeout 0;
#更改nginx页面,方便观察(两台机器分别操作)
[root@localhost ~]# cd /usr/share/nginx/html
[root@localhost html]# rm -rf *
[root@localhost html]# echo "service-1" > index.html
[root@localhost html]# echo "service-2" > index.html
#在lo接口上绑定VIP(两台机器分别操作)
[root@localhost ~]# id addr add dev lo 192.168.222.200/32
#忽略arp广播(两台机器均操作)
[root@localhost ~]# echo 1 > /proc/sys/net/ipv4/conf/all/arp_ignore
#匹配精确IP地址回包(两台机器均操作)
[root@localhost ~]# echo 2 > /proc/sys/net/ipv4/conf/all/arp_announce
#启动nginx
[root@localhost ~]# systemctl start nginx
keepalived高可用
1.实验环境
2.配置keepalived
#分别安装nginx与keepalived
[root@localhost ~]# yum -y install nginx
[root@localhost ~]# yum -y install keepalived
#更改keepalived配置文件
[root@localhost ~]# cd /etc/keepalived
[root@localhost keepalived]# ls
keepalived.conf
#先进行备份
[root@localhost ~]# cp /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.bak
[root@localhost keepalived]# vim keepalived.conf
#里面全部删除
#写一个判断nginx是否开启的脚本
[root@localhost keepalived]# vim nginx_check.sh
#!/bin/bash
curl 192.168.222.200
if [ $? -ne 0 ];then
systemctl stop keepalived
fi
#给脚本添加一个执行权限
[root@localhost keepalived]# chmod +x nginx_check.sh
#编辑配置文件
#MASTER配置如下
! Configuration File for keepalived
global_defs {
router_id directory1 #辅助改为directory2
}
vrrp_script check_nginx {
script "/etc/keepalived/nginx_check.sh"
interval 5
}
vrrp_instance VI_1 {
state MASTER #定义主还是备
interface ens33 #VIP绑定接口
virtual_router_id 80 #整个集群的调度器一致
priority 100 #back改为50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.222.200/32 # vip
}
track_script {
check_nginx
}
}
#启动nginx
[root@localhost ~]# systemctl start nginx
#启动keepalived
[root@localhost ~]# systemctl start keepalived
#配置backup