LVS之DR模式
一.前言
LVS(Linux Virtual Server)即Linux虚拟服务器,是由章文嵩博士主导的开源负载均衡项目,目前LVS已经被集成到Linux内核模块中,LVS主要用于多服务器的负载均衡。
LVS有三种工作模式,生产环境中大多使用DR模式,本文主要介绍DR模式的搭建步骤,具体的原理可百度参考其他资料。
点此查看lvs之nat模式
实验背景:
三台虚拟机来做lvs的负载均衡实验,vm01是负载均衡器,只有一块网卡,vm02和vm03是真正的web服务器
vm01(负载均衡)
eth0:192.168.1.9
vip:192.168.1.8
vm02(后端服务器)
eth1:192.168.1.11 (gateway:192.168.1.2)
vm03 (后端服务器)
eth1:192.168.1.12(gateway:192.168.1.2)
注:DR模式VIP必须跟服务器同一网段
二.负载均衡器安装
vm01上操作
yum install -y ipvsadm
lsmod |grep ip_vs
modprobe ip_vs
#判断是不是加载了ip_vs模块
lsmod |grep ip_vs
![](https://img2020.cnblogs.com/blog/1147891/202101/1147891-20210112163001656-664949006.png)
三.创建lvsdr模式启动脚本
1.vm01上创建lvsdr
vim /etc/init.d/lvsdr
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/bin/bash VIP=192.168.1.8 RIP1=192.168.1.11 RIP2=192.168.1.12 case "$1" in start) echo "start LVS of DirectorServer DR" /sbin/iptables -F /sbin/ipvsadm -C /sbin/ifconfig ens33:0 $VIP broadcast $VIP netmask 255.255.255.0 up /sbin/ipvsadm -A -t $VIP:80 -s rr /sbin/ipvsadm -a -t $VIP:80 -r $RIP1 -g /sbin/ipvsadm -a -t $VIP:80 -r $RIP2 -g /sbin/ipvsadm ;; stop) echo "stop LVS of DirectorServer DR" echo "0" >/proc/sys/net/ipv4/ip_forward /sbin/ipvsadm -C /sbin/ifconfig ens33:0 down ;; *) echo "argements error" ;; esac
添加执行权限
chown +x /etc/init.d/lvsdr
启动lvsdr
/etc/init.d/lvsdr start
2.vm02、vm03上创建lvsdrrip
vim /etc/init.d/lvsdrrip
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/bin/bash #DR server VIP=192.168.1.8 case "$1" in start) echo "start LVS of DR" /sbin/ifconfig lo:0 $VIP broadcast $VIP netmask 255.255.255.255 up /sbin/route add -host $VIP dev lo:0 echo "1" > /proc/sys/net/ipv4/conf/lo/arp_ignore echo "2" > /proc/sys/net/ipv4/conf/lo/arp_announce echo "1" > /proc/sys/net/ipv4/conf/all/arp_ignore echo "2" > /proc/sys/net/ipv4/conf/all/arp_announce ;; stop) echo "stop LVS of DR" /sbin/ifconfig lo:0 down echo "0" > /proc/sys/net/ipv4/conf/lo/arp_ignore echo "0" > /proc/sys/net/ipv4/conf/lo/arp_announce echo "0" > /proc/sys/net/ipv4/conf/all/arp_ignore echo "0" > /proc/sys/net/ipv4/conf/all/arp_announce ;; *) echo "Usage:$0 {start|stop}" esac exit 1
添加执行权限
chown +x /etc/init.d/lvsdrrip
启动lvsdrrip
/etc/init.d/lvsdrrip start
四.测试
1.vm02和vm03上安装nginx
yum -y install nginx #启动nginx nginx
vm02 修改index.html文件
echo "<h1 style='color:red;'>I am vm02</h1>" > /usr/share/nginx/html/index.html
vm03修改index.html文件
echo "<h1 style='color:green;'>I am vm03</h1>" > /usr/share/nginx/html/index.html
2.浏览器访问192.168.1.8
![](https://img2020.cnblogs.com/blog/1147891/202101/1147891-20210112171427818-1830593289.png)
3.vm01查看负载情况
ipvsadm -lnc