在Debian系统中,可以使用 iptables
或 firewalld
来实现端口转发。以下是两种方法的详细步骤:
基于 firewalld
的端口转发
firewalld
是一个动态管理防火墙的工具,适用于CentOS 7及Debian系统。以下是使用 firewalld
进行端口转发的步骤:
-
安装
firewalld
(如果尚未安装):sudo apt-get update sudo apt-get install firewalld
-
启动并启用
firewalld
服务:sudo systemctl start firewalld sudo systemctl enable firewalld
-
开启内核转发:
echo 1 > /proc/sys/net/ipv4/ip_forward
-
编辑
firewalld
配置文件: 打开/etc/firewalld/zones/public.xml
文件,并添加以下内容:Public For use in public areas. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted. -
重启
firewalld
服务以应用更改:sudo systemctl restart firewalld
基于 iptables
的端口转发
iptables
是一个强大的防火墙工具,适用于Debian和Ubuntu系统。以下是使用 iptables
进行端口转发的步骤:
-
安装
iptables
(如果尚未安装):sudo apt-get update sudo apt-get install iptables
-
启动并启用
iptables
服务:sudo systemctl start iptables sudo systemctl enable iptables
-
清空所有防火墙规则:
sudo iptables -F sudo iptables -X
-
开启内核转发:
echo 1 > /proc/sys/net/ipv4/ip_forward
或者编辑
/etc/sysctl.conf
文件,取消以下行的注释:net.ipv4.ip_forward=1
然后运行以下命令使更改生效:
sudo sysctl -p
-
添加
iptables
规则: 将本地端口8080转发到远程服务器的80端口:sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 远程服务器IP:80
为了确保数据包在本地和远程服务器之间正确传输,需要添加一个
iptables
规则,将源地址伪装为本地服务器的地址:sudo iptables -t nat -A POSTROUTING -j MASQUERADE
-
保存
iptables
规则:sudo sh -c "iptables-save > /etc/iptables/rules.v4"
-
重启
iptables
服务以应用更改:sudo systemctl restart netfilter-persistent