温馨提示×

debian防火墙怎样做端口映射

小樊
50
2026-10-05 07:41:08
栏目: 智能运维

在 Debian 上做“端口映射”通常有几种常见场景,下面按使用方式和场景给你说明,最核心的是 iptables / nftables 端口转发(DNAT)。


一、最常用:使用 iptables 做端口映射(DNAT)

示例需求

把 本机 2222 端口 映射到 内网 192.168.1.10:22

1️⃣ 开启内核转发

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

2️⃣ 添加 iptables 规则

iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to-destination 192.168.1.10:22
iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 22 -j ACCEPT

3️⃣ 如果本机有公网 IP(SNAT 可选)

iptables -t nat -A POSTROUTING -j MASQUERADE

4️⃣ 保存规则(Debian)

apt install iptables-persistent
netfilter-persistent save

二、新系统推荐:nftables(Debian 10+)

示例:2222 → 192.168.1.10:22

nft add table nat
nft add chain nat prerouting { type nat hook prerouting priority 0 \; }
nft add rule nat prerouting tcp dport 2222 dnat to 192.168.1.10:22
nft add rule nat postrouting masquerade

保存:

nft list ruleset > /etc/nftables.conf
systemctl enable nftables

三、本地端口映射(不跨机)

把 8080 映射到本机 80

iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80

或:

nft add rule nat prerouting tcp dport 8080 redirect to :80

四、用 firewalld(如果装了)

firewall-cmd --add-forward-port=port=2222:proto=tcp:toaddr=192.168.1.10:toport=22 --permanent
firewall-cmd --reload

五、SSH 端口转发(临时用)

ssh -L 0.0.0.0:2222:192.168.1.10:22 user@localhost

六、常见坑

✅ 必须开启 ip_forward
✅ FORWARD 链不能 DROP
✅ 云服务器还要放行安全组
✅ Docker 会改 iptables


如果你能告诉我:

  • Debian 版本
  • 是 本机映射 / 内网映射 / 公网映射
  • 是否使用 Docker

我可以给你精确命令。

0 踩