大网数据广告活动
服务器运维问答

Use iptables to port forward multiple ports

· 52CE 我爱测

I have services running on VPS A(1.1.1.1) on ports 30000-32000. I would like to have VPS B(2.2.2.2) to port forward them to 20000- 22000. (You may take a look at the demo graph link below to understand what I would like to achiev…

问题原文

原帖链接 · mcgag · CC BY-SA 3.0

I have services running on VPS A(1.1.1.1) on ports 30000-32000.

I would like to have VPS B(2.2.2.2) to port forward them to 20000- 22000.

(You may take a look at the demo graph link below to understand what I would like to achieve :D )

Forward to different ports

I used the command below to set up iptables:

iptables -t nat -A PREROUTING -p tcp --dport 20000:22000 -j DNAT --to-destination 1.1.1.1:30000-32000
iptables -t nat -A POSTROUTING -p tcp -d 1.1.1.1 --dport 30000:32000 -j SNAT --to-source 2.2.2.2
20000:22000
iptables -t nat -A PREROUTING -p udp --dport 20000:22000 -j DNAT --to-destination 1.1.1.1:30000-32000
iptables -t nat -A POSTROUTING -p udp -d 1.1.1.1 --dport 30000:32000 -j SNAT --to-source 2.2.2.2
20000:22000

After some tests, I find that it seems that only port 20000 was forwarding the original server's port 30000. However, other ports are not working.

I checked 4 things below: 1. VPS A (1.1.1.1)'s service Service running on ports 30000 - 32000 are fully functional

  1. VPS B port forwarding setting Upon checking sysctl on VPS B, ipv4 forwarding is enabled.

(i.e. net.ipv4.ip_forward = 1)

  1. VPS B's iptable setting. It looks fine to me. You may click on the link below for exact setting.

iptables setting

  1. I also tried to do a normal multiple port forwarding from VPS A to VPS B (i.e. VPS A (30000-32000) >> VPS B (30000-32000))

(You may take a look at the demo graph link below for what I would like to achieve :D )

Everything is working fine.

I really have no idea how to achieve it. Any help is appreciated! Thank you in advance!

社区高分解答

原帖链接 · Mikhail Khirgiy · CC BY-SA 3.0

You need to change iptables rules. Your DNAT rule doesn't filter destination IP address for incoming traffic from users. Your SNAT rule doesn't filter source IP address and source port 30000:32000 range for incoming traffic from A server. You need on B server:

iptables -t nat -A PREROUTING -p tcp -d 2.2.2.2 --dport 20000:22000 -j DNAT --to-destination 1.1.1.1:30000-32000
iptables -t nat -A POSTROUTING -p tcp -s 1.1.1.1 --sport 30000:32000 -j SNAT --to-source 2.2.2.2:20000:22000

iptables -t nat -A PREROUTING -p udp -d 2.2.2.2 --dport 20000:22000 -j DNAT --to-destination 1.1.1.1:30000-32000
iptables -t nat -A POSTROUTING -p udp -s 1.1.1.1 --sport 30000:32000 -j SNAT --to-source 2.2.2.2:20000:22000

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-10-01)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。