[英]Docker compose - port forward from host IP to specific IP in container
I have a container that sits in multiple networks, and specifically two "external" networks.我有一个位于多个网络中的容器,特别是两个“外部”网络。
The host also has two NICs and I need to forward from one host IP to a specific IP on the container, and then forward the other host IP to the other IP on the container.主机也有两个网卡,我需要从一个主机 IP 转发到容器上的特定 IP,然后将另一个主机 IP 转发到容器上的另一个 IP。
For example, take this docker compose segment:例如,以这个 docker compose 段为例:
services:
server:
image: image
networks:
internal_net:
ipv4_address: 1.0.0.1
ext1_net:
ipv4_address: 1.1.1.1
ext2_net:
ipv4_address: 2.2.2.2
And say on the host on eth0 I have 3.3.3.3 and on eth1 I have 4.4.4.4在 eth0 上的主机上说我有 3.3.3.3,在 eth1 上我有 4.4.4.4
I would then want to forward 80 from 3.3.3.3 on the host to 1.1.1.1 on the container, I would then want to forward 80 from 4.4.4.4 on the host to 2.2.2.2 on the container然后我想将 80 从主机上的 3.3.3.3 转发到容器上的 1.1.1.1,然后我想将 80 从主机上的 4.4.4.4 转发到容器上的 2.2.2.2
However, the ports option doesn't seem to allow forwarding to a specific container interface.但是,ports 选项似乎不允许转发到特定的容器接口。
How do I achieve this?我如何实现这一目标? Do I need to do the iptables rules manually?
我需要手动执行 iptables 规则吗?
Many thanks非常感谢
When Docker sets up the forwarding rule to publish a container port on the host, it looks like it always chooses the address of the first interface.当 Docker 设置转发规则在主机上发布容器端口时,看起来它总是选择第一个接口的地址。 So given a configuration like this:
所以给定这样的配置:
services:
server:
image: image
ports:
- "8080:8080"
networks:
internal_net:
ipv4_address: 1.0.0.1
ext1_net:
ipv4_address: 1.1.1.1
ext2_net:
ipv4_address: 2.2.2.2
Docker would create something like this rule in the nat
table: Docker 会在
nat
表中创建类似以下规则的内容:
-A DOCKER ! -i br-439dfcc4c0d7 -p tcp -m tcp --dport 8080 -j DNAT --to-destination 1.0.0.1:8080
If you wanted to explicitly target a different address, you would exclude the ports
entry from your docker-compose.yaml
and add your own rules to the PREROUTING
chain of the nat
table.如果您想显式定位不同的地址,您可以从
docker-compose.yaml
中排除ports
条目,并将您自己的规则添加到nat
表的PREROUTING
链中。 For example:例如:
iptables -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination
1.1.1.1:8080
Communication from your container back to your host is going to be governed by the routing table inside the container.从容器到主机的通信将由容器内的路由表控制。 Typically, the default route will be via
eth0
, so your container will not necessarily reply over the interface you expect.通常,默认路由将通过
eth0
,因此您的容器不一定会通过您期望的接口进行回复。 Because Docker creates MASQUERADE
rules for all the addresses in your container this should not be a problem.因为 Docker 为容器中的所有地址创建
MASQUERADE
规则,所以这应该不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.