当前位置: > CentOS > CentOS教程 >

iptables 做内网映射到公网地址

时间:2020-04-08 11:01来源:linux.it.net.cn 作者:IT
案例:在一组集群中,只有内网的服务器需要走反代的公网出去。
内网某台服务器ip:192.168.142.82
反代的内网ip:192.168.142.90

1.内网服务器的网卡的网关设置成192.168.142.90
#cat ifcfg-enp2s0f1
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=enp2s0f1
UUID=bf571909-2c48-466a-b765-b73b49d90d68
DEVICE=enp2s0f1
ONBOOT=yes
IPADDR=192.168.142.82
GATEWAY=192.168.142.90 #这是网关地址,也是反代的内网ip
DNS1=8.8.8.8
PREFIX=24
IPV6_PRIVACY=no
ZONE=public

1.1重启网阿卡
ifdown 网卡名称
ifup 网卡名称

2.然后去反代机器设置iptables snat
vim /etc/sysconfig/iptables
#Generated by iptables-save v1.4.21 on Wed May 22 16:59:50 2019
*filter
:INPUT DROP [14:1070]
:FORWARD ACCEPT [130:21296]
:OUTPUT ACCEPT [267:51219]
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp -s 192.168.142.0/24 --dport 8080 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p icmp --icmp-type echo-request -j ACCEPT
-A INPUT -p tcp -m tcp --dport 10050 -j ACCEPT
COMMIT
#Completed on Mon Aug 5 15:51:35 2019
#Generated by iptables-save v1.4.21 on Mon Aug 5 15:51:35 2019
*nat
:PREROUTING ACCEPT [22552217:1377073778]
:INPUT ACCEPT [1179546:51768441]
:OUTPUT ACCEPT [375097:27372482]
:POSTROUTING ACCEPT [373955:27301058]

#这里我们将整个ip段的内网snat到了22.22.22.22的公网地址
-A POSTROUTING -s 192.168.142.0/24 -j SNAT --to-source 22.22.22.22

COMMIT
#Completed on Mon Aug 5 15:51:35 2019

2.1在转发机上配置如下两步,打开内核参数
[root@localhost ~]# sysctl -w net.ipv4.ip_forward=1
[root@localhost ~]# sysctl -a|grep ip_forward
net.ipv4.ip_forward = 1
net.ipv4.ip_forward_use_pmtu = 0

2.2保存重启iptables
service iptables restart ##在配置文件编辑的不需要再service iptables save 不然会不成功。

ok搞定了!!!



(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容