CentOS 7 下用 firewall-cmd / iptables 实现 NAT 转发供内网服务器联网

2020-09-10
0评论
/
945阅读
爱搜啊

自从用 HAProxy 对服务器做了负载均衡以后,感觉后端服务器真的没必要再配置并占用公网IP资源。

而且由于托管服务器的公网 IP 资源是固定的,想上 Keepalived 的话,需要挤出来 3 个公网 IP 使用,所以更加坚定了让负载均衡后端服务器释放公网 IP 的想法。

可是,后端服务器也不是简单释放公网 IP 就能正常工作的,正在运行的系统很多模块依然需要具有连接外网获取数据的能力。

CentOS 7 下用 firewall-cmd / iptables 实现 NAT 转发供内网服务器联网

所以就想到了用 CentOS 做一个软路由(内网 NAT 转发),如果能实现的话,就满足了我的需求。

搜索并试验了一番,目前发现用 iptables 是可行的,而且已经被我验证有效的方案。

由于用到了 iptables,需要停止并禁用内置的 firewalld 防火墙服务。

停止内置的 firewalld

systemctl stop firewalld
systemctl disable firewalld

打开系统的 IP 转发功能

echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p

安装 iptables 服务

yum -y install iptables-services
# 移除 iptables 服务
#yum -y remove iptables-services

查看 iptables 规则

iptables -L

清空默认的 filter 表

iptables -F

清空默认的 nat

iptables -t nat -F

默认规则,禁止所有入站,允许所有出站

iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT

默认规则,允许所有本地环回通信,出入站

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

重点,开启 NAT 功能

iptables -t nat -A POSTROUTING -j MASQUERADE

完整的命令

可以在命令行下粘贴批量执行

systemctl stop firewalld
systemctl disable firewalld

yum -y install iptables-services


iptables -F
iptables -t nat -F
iptables -P INPUT  DROP
iptables -P OUTPUT ACCEPT
iptables -t nat -A POSTROUTING -j MASQUERADE

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A INPUT -p udp --dport 53 -j ACCEPT
iptables -A INPUT -p tcp --dport 53 -j ACCEPT
iptables -A INPUT -p tcp -s 192.168.66.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -s 你的可信任远程管理IP -j ACCEPT


iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT


iptables-save > /etc/sysconfig/iptables
systemctl restart iptables

其他

echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p0

后记,补充 2017-12-13 20:28

捣鼓了一下午,NAT 转发当路由器供内网服务器上网终于搞定了,结果CentOS重启后,发现 iptables 的配置丢失,竟然没有永久保存?

太扯淡!

网上说这个问题的还很多,有人说可以制作自启动脚本,在启动时自动将 iptables 的规则重新注册一次,

也算是一个解决办法。

不过,思来想起,既然 CentOS 已经抛弃了 iptables ,那肯定是有一定道理的,firewalld 一定也有办法实现同样的功能吧!

echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p1

搞定了。详细《CentOS 7下配置firewalld(firewall-cmd)实现NAT转发软路由


本站附件分享,如果附件失效,可以去找找看

诚通网盘附件百度网盘附件


于2020-09-10发布