温馨提示×

debian防火墙端口如何映射

小樊
49
2026-09-23 15:03:36
栏目: 智能运维

在 Debian 中,“端口映射”通常有两种理解:

  1. 本机端口转发(Port Redirection):比如把访问 80 端口的流量转到 8080
  2. 防火墙/NAT 端口映射(Port Forwarding):比如把公网 IP 的某个端口映射到内网某台机器的端口

下面分别说明(以 Debian + iptables / nftables 为主)。


一、本机端口映射(端口转发)

方法 1:使用 iptables(传统方式)

开启 IP 转发(如果已是本机转发可不改):

sysctl -w net.ipv4.ip_forward=1

示例:把 本机 80 端口 映射到 本机 8080 端口

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

如果是本地访问(localhost):

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

查看规则:

iptables -t nat -L -n -v

方法 2:使用 nftables(Debian 新推荐)

编辑 /etc/nftables.conf:

table ip nat {
    chain prerouting {
        type nat hook prerouting priority 0;
        tcp dport 80 redirect to 8080
    }
}

应用:

nft -f /etc/nftables.conf

二、防火墙端口映射(NAT 端口转发)

示例:
公网 IP:1.2.3.4
内网机器:192.168.1.10
需求:访问 1.2.3.4:2222 → 192.168.1.10:22

iptables 方式

开启转发:

sysctl -w net.ipv4.ip_forward=1

DNAT(入口):

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

SNAT(回包):

iptables -t nat -A POSTROUTING -p tcp -d 192.168.1.10 --dport 22 -j MASQUERADE

允许转发:

iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 22 -j ACCEPT

nftables 方式

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

三、使用 firewalld(如已安装)

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

四、常见注意点

  • Debian 10+ 默认推荐 nftables
  • 修改后最好写入开机启动(iptables-save / nft 配置文件)
  • 云服务器还需在安全组放行端口
  • 如果只做“端口转发”,服务本身可不监听在公网

如果你能说明:

  • Debian 版本
  • 用的是 iptables / nftables / firewalld
  • 是「本机映射」还是「外网映射到内网」

我可以给你更精确的命令。

0 踩