我有个码头集装箱在运行詹金斯。作为构建过程的一部分,我需要访问在主机上本地运行的web服务器。是否有一种方法可以将主机web服务器(可以配置为在端口上运行)暴露给jenkins容器?

我在Linux机器上本机运行docker。

更新:

除了下面的@larsks答案,要从主机上获取主机IP的IP地址,我做了以下操作:

ip addr show docker0 | grep -Po 'inet \K[\d.]+'

当前回答

在docker run命令中使用——net="host",那么docker容器中的localhost将指向docker主机。

其他回答

对于linux系统,从docker引擎的主版本20.04开始,您现在也可以通过host.docker.internal与主机通信。这不会自动工作,但你需要提供以下运行标志:

--add-host=host.docker.internal:host-gateway

See

https://github.com/moby/moby/pull/40007#issuecomment-578729356 https://github.com/docker/for-linux/issues/264#issuecomment-598864064

答案是……

将http://127.0.0.1或http://localhost替换为http://host.docker.internal。

Why?

Docker文档中的源代码。

我的谷歌搜索把我带到了这里,在挖掘评论后,我发现它是从Docker容器内部复制的,我如何连接到机器的本地主机?我投票认为这是重复的,但由于人们(包括我自己!)经常向下滚动答案,而不是仔细阅读评论,这里是一个简短的答案。

对我来说(Windows 10, Docker Engine v19.03.8),它是https://stackoverflow.com/a/43541732/7924573和https://stackoverflow.com/a/50866007/7924573的组合。

change the host/ip to host.docker.internal e.g.: LOGGER_URL = "http://host.docker.internal:8085/log" set the network_mode to bridge (if you want to maintain the port forwarding; if not use host): version: '3.7' services: server: build: . ports: - "5000:5000" network_mode: bridge or alternatively: Use --net="bridge" if you are not using docker-compose (similar to https://stackoverflow.com/a/48806927/7924573) As pointed out in previous answers: This should only be used in a local development environment. For more information read: https://docs.docker.com/compose/compose-file/#network_mode and https://docs.docker.com/docker-for-windows/networking/#use-cases-and-workarounds

这是一个老问题,有很多答案,但没有一个足够适合我的背景。在我的例子中,容器非常精简,不包含从容器中提取主机ip地址所需的任何网络工具。

此外,使用——net="host"方法是一种非常粗略的方法,当人们希望使用多个容器进行良好隔离的网络配置时,这种方法并不适用。

因此,我的方法是在主机侧提取主机的地址,然后用——add-host参数将其传递给容器:

$ docker run --add-host=docker-host:`ip addr show docker0 | grep -Po 'inet \K[\d.]+'` image_name

或者,将主机的IP地址保存在一个环境变量中,以后再使用:

$ DOCKERIP=`ip addr show docker0 | grep -Po 'inet \K[\d.]+'`
$ docker run --add-host=docker-host:$DOCKERIP image_name

然后docker-host被添加到容器的hosts文件中,你可以在你的数据库连接字符串或API url中使用它。

为此我创建了一个docker容器https://github.com/qoomon/docker-host

然后,您可以简单地使用容器名称dns访问主机系统。 curl http://dockerhost: 9200