通过Docker Compose访问主机
我有一个启动容器的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}'
这样的东西ifconfig | grep broadcast | awk '{print $2}'
ifconfig | grep broadcast | awk '{print $2}'
来获取IP并replace为Docker Compose。 由于这个IP可以改变重新连接,不同的设置可以有不同的ifconfig
结果,我正在寻找一个更好的解决scheme。
我在docker问题#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的主机的名称。 如上所述,这是基于:
- https://github.com/docker/docker/issues/1143#issuecomment-39364200
(…)一种方法是依靠Docker主机可通过Docker桥的地址访问的事实,Docker桥正好是容器的默认网关。 换句话说,巧妙的parsing
ip route ls | grep ^default
在这种情况下,ip route ls | grep ^default
可能就是你所需要的。 当然,它依赖于一个实现细节(默认网关恰好是Docker主机的IP地址),将来可能会改变。 (……) - https://github.com/docker/docker/issues/1143#issuecomment-46105218
(…)很多像我们这样的人都在寻找这样一个小珍闻
netstat -nr | grep '^0\.0\.0\.0' | awk '{print $2}'
netstat -nr
意思是 :
Netstat打印有关Linuxnetworking子系统的信息。
(……)
– 路由,-r
显示内核路由表。
(……)
– 数字,-n
显示数字地址,而不是尝试确定符号主机,端口或用户名。
这是Docker Compose的一个已知问题:请参阅文档如何从容器#1143连接到Docker主机 。 /etc/hosts
中的dockerhost
条目的build议解决scheme未实现。
我在这个问题上用一个shellvariables来解决这个问题:
创build一个LOCAL_XX_HOST
variables: export LOCAL_XX_HOST="http://$(ifconfig en0 inet | grep "inet " | awk -F'[: ]+' '{ print $2 }'):3001"
。
然后,例如,在docker-compose
引用此variables,如下所示:
my-thingy: image: my-image:latest environment: - THE_HOST_I_WANT_TO_CONNECT_TO=${LOCAL_XX_HOST}