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

自从用 HAProxy 对服务器做了负载均衡以后,感觉后端服务器真的没必要再配置并占用公网IP资源。
而且由于托管服务器的公网 IP 资源是固定的,想上 Keepalived 的话,需要挤出来 3 个公网 IP 使用,所以更加坚定了让负载均衡后端服务器释放公网 IP 的想法。
可是,后端服务器也不是简单释放公网 IP 就能正常工作的,正在运行的系统很多模块依然需要具有连接外网获取数据的能力。

所以就想到了用 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



☼ 其他

# 允许已建立的传入连接
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# 允许DHCP传入连接
iptables -A INPUT -i eth1 -p udp --dport 67:68 -j ACCEPT

# 默认禁止路由转发
iptables -P FORWARD DROP

# 允许内网路由转发
iptables -A FORWARD -s 192.168.66.0/24 -j ACCEPT

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

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

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

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


firewall-cmd --permanent --zone=public --add-masquerade

# 调整防火墙策略,开放 vrrp 协议,给 Keepalived 使用
# 否则可能导致【脑裂】问题,争抢VIP,或者master挂掉之后backup无法正常工作
firewall-cmd --direct --permanent --add-rule ipv4 filter INPUT 0 --in-interface ens33 --protocol vrrp -j ACCEPT
firewall-cmd --reload
#

搞定了。

当然其他功能端口的开放,这里就不啰嗦了 (0^0)。

posted on 2017-12-13 16:59  观摩  阅读(6682)  评论(0编辑  收藏  举报