2016-10-03 20 views
0

我有一个启动容器的Docker Compose v2文件。我本地在端口3001上运行服务。我想从Docker容器中获得此服务。使用Docker Compose到达主机

泊坞窗撰写文件看起来是这样的:

version: '2' 
services: 
    my-thingy: 
    image: my-image:latest 
    #network_mode: host #DOES not help 
    environment: 
     - THE_HOST_I_WANT_TO_CONNECT_TO=http://127.0.0.1:3001 
    ports: 
    - "3010:3010" 

现在,我怎么能达到THE_HOST_I_WANT_TO_CONNECT_TO

我想的是:

  • 设置network_mode主办。这没有奏效。无法达到127.0.0.1。
  • 我也可以看到,如果我使用主机的本地IP,我可以从容器到达主机。一个简单的方法就是使用类似ifconfig | grep broadcast | awk '{print $2}'的东西来获取IP并在Docker Compose中替换它。由于这个IP可以在重新连接时改变,并且不同的设置可以有不同的结果,所以我在寻找更好的解决方案。

回答

1

我用另一个黑客/ workarkound从docker issue #1143意见。似乎为我工作™对于被...具体来说,我在我的Dockerfile添加以下行时间:

# - net-tools contains netstat, used to discover IP of Docker host server. 
# NOTE: the netstat trick is to make Docker host server accessible 
# from inside Docker container under name 'dockerhost'. Unfortunately, 
# as of 2016.10, there's no official/robust way to do this when Docker host 
# has no public IP/DNS entry. What is used here is built based on: 
# - https://github.com/docker/docker/issues/1143#issuecomment-39364200 
# - https://github.com/docker/docker/issues/1143#issuecomment-46105218 
# See also: 
# - http://stackoverflow.com/q/38936738/98528 
# - https://github.com/docker/docker/issues/8395#issuecomment-200808798 
# - https://github.com/docker/docker/issues/23177 
RUN apt-get update && apt-get install -y net-tools 
CMD (netstat -nr | grep '^0\.0\.0\.0' | awk '{print $2" dockerhost"}' >> /etc/hosts) && \ 
     ...old CMD... 

有了这个,我可以使用dockerhost作为主机的名称Docker安装在哪里。正如上面提到的,这是基于:

其中netstat -nr means

的Netstat打印有关Linux网络子系统的信息。
(...)
--route,-r
显示内核路由表。
(...)
--numeric,-n
显示的数字地址,而不是试图确定象征性的主机,端口或用户名。

0

这是Docker Compose的已知问题:请参阅Document how to connect to Docker host from container #1143/etc/hosts中的dockerhost条目的建议解决方案未实现。

我去同一个shell变量这也如同a comment对这个问题提出由amcdl解决方案:

创建LOCAL_XX_HOST变量:export LOCAL_XX_HOST="http://$(ifconfig en0 inet | grep "inet " | awk -F'[: ]+' '{ print $2 }'):3001"

然后,例如,是指该变量在docker-compose这样的:

my-thingy: 
    image: my-image:latest 
    environment: 
     - THE_HOST_I_WANT_TO_CONNECT_TO=${LOCAL_XX_HOST} 
相关问题