通过主机映射端口进行容器到容器的通信

时间:2016-03-08 20:36:21

标签: docker

我正在使用Docker版本1.9.1和docker-compose 1.5.2与--x-networking(实验网络)。

我用docker-compose up启动一个简单的节点应用程序;此应用程序将端口8000映射到主机上的端口9999。

从主持人我可以卷曲http://localhost:9999;或http://[host-ip]:9999;或者主机拥有的任何172.x.0.1地址,它们都可以工作。

我使用docker-compose up启动另一个应用程序。如果我尝试卷曲http://[host-ip]:9999或任何http://172.x.0.1地址,则由于iptables条目而丢弃数据包 - 特别是指定从此容器的子网到第一个容器的DROP的条目。 / p>

我知道可能不允许容器到容器的通信,但我的第二个容器如何通过主机上映射的端口与第一个容器通信?

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
DROP       all  --  172.17.0.0/16        172.19.0.0/16
DROP       all  --  172.19.0.0/16        172.17.0.0/16
DROP       all  --  172.18.0.0/16        172.19.0.0/16
DROP       all  --  172.19.0.0/16        172.18.0.0/16
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
DROP       all  --  172.17.0.0/16        172.18.0.0/16
DROP       all  --  172.18.0.0/16        172.17.0.0/16
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain DOCKER (3 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             172.18.0.2           tcp dpt:8000

2 个答案:

答案 0 :(得分:0)

当然允许容器到容器的通信。您可以使用防火墙规则等禁止它... 您实际需要的是将这两个容器放在同一子网中。所以你需要用

创建一个子网

docker network create --subnet=172.18.0.0/16 mySubNet

然后使用

运行容器

docker run --net mynet123

就是这样。此外,在运行时,您可以使用--ip为容器分配静态IP,使用--hostname分配主机名,或使用--add-host添加其他主机条目。

编辑:我现在看到您的泊坞版本,所以我必须说我在这里写的内容适用于 docker 1.10.x

答案 1 :(得分:0)

子网解决方案

您可以为容器创建子网,但为了保持清洁,您需要为每个分布式应用程序创建子网以隔离它们。这不是最简单,也不是最简单的方法。

--link解决方案

另一种解决方案是链接您的容器。我建议你阅读this comment,所以我不会复制/粘贴其内容;)