在 Ubuntu 下使用 iptables 做端口/流量转发,常见场景有:
下面按常见用法说明。
如果是跨网卡/跨机器转发,必须先开启:
# 临时开启
sudo sysctl -w net.ipv4.ip_forward=1
# 永久开启
sudo vim /etc/sysctl.conf
添加或修改:
net.ipv4.ip_forward=1
生效:
sudo sysctl -p
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80
✅ 适合:
⚠️ 只对本机外部访问有效,本机 localhost 访问 8080 不会转发(除非加 OUTPUT 规则)。
sudo iptables -t nat -A OUTPUT -p tcp --dport 8080 -j REDIRECT --to-port 80
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 \
-j DNAT --to-destination 192.168.1.10:80
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
或指定出口网卡:
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -t nat -A PREROUTING -s 10.0.0.0/24 \
-p tcp --dport 3306 \
-j DNAT --to-destination 192.168.1.20:3306
Ubuntu 默认 不会自动保存 iptables。
sudo apt install iptables-persistent
sudo netfilter-persistent save
规则保存在:
/etc/iptables/rules.v4
查看:
sudo iptables -t nat -L -n -v
删除(按编号):
sudo iptables -t nat -L --line-numbers
sudo iptables -t nat -D PREROUTING 1
清空(谨慎):
sudo iptables -t nat -F
❌ 只加 DNAT 没加 MASQUERADE → 内网机器回包不正常
❌ 没开 ip_forward → 转发不生效
❌ ufw 和 iptables 混用 → 规则被覆盖
# 开启转发
sysctl -w net.ipv4.ip_forward=1
# 8080 -> 80
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80
# 公网 80 -> 内网
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to 192.168.1.10:80
iptables -t nat -A POSTROUTING -j MASQUERADE
如果你能告诉我:
我可以给你精确可用的规则。