Debian防火墙端口转发常用工具为iptables和firewalld,以下是具体配置方法:
一、使用iptables(推荐)
-
启用内核转发
编辑/etc/sysctl.conf,取消#net.ipv4.ip_forward=1的注释,或直接执行:sudo sysctl -w net.ipv4.ip_forward=1 sudo sysctl -p # 使配置生效 -
添加端口转发规则
- 转发外部端口到内部IP(如将外部8080转发到内部192.168.1.100的80端口):
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80 sudo iptables -t nat -A POSTROUTING -j MASQUERADE # 伪装源地址 - 保存规则(避免重启失效):
sudo apt install iptables-persistent sudo netfilter-persistent save sudo netfilter-persistent reload
- 转发外部端口到内部IP(如将外部8080转发到内部192.168.1.100的80端口):
-
验证规则
sudo iptables -t nat -L -n -v # 查看NAT规则
二、使用firewalld(需安装)
-
安装并启动服务
sudo apt update sudo apt install firewalld sudo systemctl enable --now firewalld -
配置端口转发
编辑/etc/firewalld/zones/public.xml,添加规则(示例转发本地8080到远程192.168.1.100:80):<forward-port to-addr="192.168.1.100" to-port="80" protocol="tcp" port="8080"/>重启服务生效:
sudo systemctl restart firewalld
注意事项
- 确保目标IP和端口可访问,云服务器需放行安全组规则。
ufw默认基于iptables,若需高级转发仍需直接操作iptables。- 生产环境建议限制转发源IP,避免暴露敏感端口。
参考来源: