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

Iptables port forwarding on Ubuntu (Docker)

· 52CE 我爱测

I have an Ubuntu Docker image running in Kubernetes and I'm trying to set up port forwarding to route requests coming in on port 5000 to a different destination and port (10.30.8.191:443). I installed iptables (not installed by d…

问题原文

原帖链接 · PoweredByOrange · CC BY-SA 4.0

I have an Ubuntu Docker image running in Kubernetes and I'm trying to set up port forwarding to route requests coming in on port 5000 to a different destination and port (10.30.8.191:443). I installed iptables (not installed by default) and added the following rules:

iptables -A PREROUTING -t nat -p tcp --dport 5000 -j DNAT --to 10.30.8.191:443
iptables -A FORWARD -p tcp -d 10.30.8.191 --dport 443 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

I also verified /proc/sys/net/ipv4/ip_forward is set to 1. However, making a curl call to https://127.0.0.1:5000 results in connection refused. I have verified that the destination ip 10.30.8.191 is directly accessible from this host.

Any ideas what I might be missing? I haven't specified an interface in my iptables rules, which to my understanding means the rules should apply to all existing interfaces. Is that not the case?

已采纳解答

原帖链接 · Anton Danilov · CC BY-SA 4.0

  • Local originated packets don't pass through nat/PREROUTING chain. To make request to 127.0.0.1:5000 success you should add same DNAT rule into nat/OUTPUT chain:
iptables -t nat -A OUTPUT \
         -d 127.0.0.1 -p tcp --dport 5000 \
    -j DNAT --to 10.30.8.191:443
  • It also requires the changing of net.ipv4.conf.lo.route_localnet variable:
sysclt -w net.ipv4.conf.lo.route_localnet=1
  • Reply packets should pass through your ubuntu host, otherwise you get the routing triangle issue. To do it you should add SNAT rule:
iptables -t nat -A POSTROUTING \
         -d 10.30.8.191 -p tcp --dport 443 \
         -m conntrack --ctstate DNAT --ctorigdstport 5000 \
    -j MASQUERADE

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

资料来源与适用范围

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

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

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