NAT模式
实验拓扑
负载均衡器
1、开启路由转发
vi /etc/sysctl.conf # 开启路由转发功能
net.ipv4.ip_forward=1
sysctl -p
2、SNAT,这一步要开启防火墙,并创建规则
首先开启防火墙
[root@localhost ~]# service iptables start
iptables:应用防火墙规则: [确定]
[root@localhost ~]# chkconfig iptables on
[root@localhost ~]# iptables -F 清空原始的默认规则
创建规则
[root@localhost ~]# iptables -t nat -A POSTROUTING -s 10.10.10.0/24 -o eth0 -j SNAT --to-source 20.20.20.11
# 添加防火墙记录,当源地址是 内网网段(10.10.10.0/24) 并且出口网卡为 eth0 的时候进行 SNAT 转换,转换源地址为外网卡地址(20.20.20.11)
[root@localhost ~]# iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
SNAT all -- 10.10.10.0/24 anywhere to:20.20.20.11
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
#重启后会失效,所以持久化保存
[root@localhost ~]# service iptables save
iptables:将防火墙规则保存到 /etc/sysconfig/iptables: [确定]
3、添加集群即集群节点
# 添加 ipvsadm TCP 集群
ipvsadm -A -t 20.20.20.11:80 -s rr
# 添加 ipvsadm 节点 NAT模式支持端口映射 对于10.10.10.13做8080端口
ipvsadm -a -t 20.20.20.11:80 -r 10.10.10.12:80 -m
ipvsadm -a -t 20.20.20.11:80 -r 10.10.10.13:8080 -m
-m NAT模式
--masquerading -m masquerading (NAT)
检查ipvsadm情况
持久化保存,并加入开启自启
service ipvsadm save # 保存 ipvs 集群设置到文件进行持久化
chkconfig ipvsadm on
service ipvsadm restart
真实服务器
1、将网关指向负载均衡器
vim /etc/sysconfig/network-scripts/ifcfg-eth2
修改其GATEWAY参数的值为10.10.10.11
echo "GATEWAY=10.10.10.11" >> /etc/sysconfig/network-scripts/ifcfg-eth2
重启网卡使其生效,检查路由是否与预期相符
service network restart
2、重启Web服务器
RS1
[root@localhost ~]#service httpd start
[root@localhost ~]#echo "this is RS1" > /var/www/html/index.html
[root@localhost ~]#service httpd restart
RS2
[root@localhost ~]#service httpd start
[root@localhost ~]#echo "this is RS2" > /var/www/html/index.html
[root@localhost ~]#service httpd restart
3、由于负载均衡服务器添加的集群的子节点是端口映射的10.10.10.13:8080 那么RS2就要监听8080这个端口
[root@localhost ~]# vim /etc/httpd/conf/httpd.conf
重启服务,测试Web服务器的访问
[root@localhost ~]# service httpd restart
停止 httpd: [确定]
正在启动 httpd:httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain for ServerName
[确定]
测试
可见,与与期限相符
检查负载均衡服务器,由于使用的是NAT模式,入和出都有流量数据包产生