在 CentOS 上使用 iptables 做 NAT,常见场景是作为网关/软路由,让内网机器通过这台 CentOS 上网(SNAT / MASQUERADE),或把外部流量转发到内网(DNAT)。
下面按常见用法说明(以 CentOS 7 为例,使用 iptables 而非 firewalld)。
sysctl -w net.ipv4.ip_forward=1
编辑 /etc/sysctl.conf
net.ipv4.ip_forward = 1
然后执行:
sysctl -p
假设:
eth0(公网 IP:1.2.3.4)eth1(内网网段:192.168.1.0/24)iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 1.2.3.4
例如:
iptables -t nat -A PREROUTING -d 1.2.3.4 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.10:80
同时需要允许转发:
iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 80 -j ACCEPT
如果默认 FORWARD 策略是 DROP:
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
yum install iptables-services -y
service iptables save
# 或
iptables-save > /etc/sysconfig/iptables
systemctl enable iptables
systemctl stop firewalld
systemctl disable firewalld
iptables -t nat -L -n -v
cat /proc/sys/net/ipv4/ip_forward
sysctl -w net.ipv4.ip_forward=1
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
如果你能告诉我:
我可以给你一套可直接用的配置。