部署基于TUN的LVS负载均衡

322 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

一、系统资源规划

节点名称系统名称CPU/内存网卡磁盘IP地址OS
LVSlvs2C/4Gens33/tunl064G192.168.0.10/192.168.0.100CentOS7
Server1server12C/4Gens33/tunl064G192.168.0.11/192.168.0.100CentOS7
Server2server22C/4Gens33/tunl064G192.168.0.12/192.168.0.100CentOS7
Clientclient2C/4Gens3364G192.168.0.20CentOS7

二、系统软件安装与设置

如未指定,下述命令在所有节点执行!

1、安装基本软件

yum -y install vim net-tools tcpdump bash-completion

image.png

2、设置名称解析

echo 192.168.0.10 lvs >> /etc/hosts
echo 192.168.0.11 server1 >> /etc/hosts
echo 192.168.0.12 server2 >> /etc/hosts
echo 192.168.0.20 client >> /etc/hosts
echo 192.168.0.100 vip >> /etc/hosts

image.png

3、设置NTP

yum -y install chrony

image.png

systemctl start chronyd
systemctl enable chronyd
systemctl status chronyd

image.png

chronyc sources

image.png

4、设置防火墙、SELinux

systemctl stop firewalld
systemctl disable firewalld
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config

image.png

三、部署基于TUN的LVS负载均衡

1、设置LVS后端服务

在Server节点上加载ipip模块,并设置开机自动加载:

modprobe ipip

image.png

echo /usr/sbin/modprobe ipip >> /etc/rc.local
chmod +x /etc/rc.d/rc.local

image.png

在Server节点上设置内核参数:

cat > /etc/sysctl.conf << EOF
net.ipv4.conf.tunl0.arp_ignore = 1
net.ipv4.conf.tunl0.arp_announce = 2
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.tunl0.rp_filter = 0
net.ipv4.conf.all.rp_filter = 0
EOF

image.png

sysctl -p

image.png 在Server节点上添加tunl0接口地址,并设置开机自动添加:

ip address add 192.168.0.100 dev tunl0
ip link set up tunl0

image.png

echo /usr/sbin/ip address add 192.168.0.100 dev tunl0 >> /etc/rc.local
echo /usr/sbin/ip link set up tunl0 >> /etc/rc.local
chmod +x /etc/rc.d/rc.local

image.png

在Server节点上安装httpd:

yum -y install httpd

image.png

在Server1节点上配置index文件:

echo Server1 > /var/www/html/index.html

image.png

在Server2节点上配置index文件:

echo Server2 > /var/www/html/index.html

image.png

在Server节点上启动Apache,并设置自启动:

systemctl start httpd
systemctl enable httpd
systemctl status httpd

image.png

2、设置LVS负载均衡

在LVS节点上安装ipvsadm:

yum -y install ipvsadm

image.png

在LVS节点上添加tunl0接口地址,并设置开机自动添加:

ip address add 192.168.0.100 dev tunl0
ip link set up tunl0

image.png

echo /usr/sbin/ip address add 192.168.0.100 dev tunl0 >> /etc/rc.local
echo /usr/sbin/ip link set up tunl0 >> /etc/rc.local
chmod +x /etc/rc.d/rc.local

image.png

3、设置负载均衡策略

在LVS节点上设置调度策略:

ipvsadm -C
ipvsadm -A -t 192.168.0.100:80 -s rr
ipvsadm -a -t 192.168.0.100:80 -r 192.168.0.11:80 -i
ipvsadm -a -t 192.168.0.100:80 -r 192.168.0.12:80 -i
ipvsadm -ln

image.png

ipvsadm-save > /etc/sysconfig/ipvsadm
cat /etc/sysconfig/ipvsadm

image.png

四、验证基于TUN的LVS负载均衡

在Client节点上验证调度策略:

while true; do curl 192.168.0.100; sleep 2; done

image.png

在Server1节点上抓包分析:

tcpdump -i ens33 tcp port 80

image.png 客户端访问VIP地址,LVS仅处理数据请求,而让真实服务器响应数据包直接返回给客户端