我有个码头集装箱在运行詹金斯。作为构建过程的一部分,我需要访问在主机上本地运行的web服务器。是否有一种方法可以将主机web服务器(可以配置为在端口上运行)暴露给jenkins容器?
我在Linux机器上本机运行docker。
更新:
除了下面的@larsks答案,要从主机上获取主机IP的IP地址,我做了以下操作:
ip addr show docker0 | grep -Po 'inet \K[\d.]+'
我有个码头集装箱在运行詹金斯。作为构建过程的一部分,我需要访问在主机上本地运行的web服务器。是否有一种方法可以将主机web服务器(可以配置为在端口上运行)暴露给jenkins容器?
我在Linux机器上本机运行docker。
更新:
除了下面的@larsks答案,要从主机上获取主机IP的IP地址,我做了以下操作:
ip addr show docker0 | grep -Po 'inet \K[\d.]+'
当前回答
对我来说(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
其他回答
在docker run命令中使用——net="host",那么docker容器中的localhost将指向docker主机。
为此我创建了一个docker容器https://github.com/qoomon/docker-host
然后,您可以简单地使用容器名称dns访问主机系统。 curl http://dockerhost: 9200
对我来说最简单的选择是, 我使用我的机器在本地网络上的IP地址(由路由器分配)
您可以使用ifconfig命令找到这一点
e.g
ifconfig
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=400<CHANNEL_IO>
ether f0:18:98:08:74:d4
inet 192.168.178.63 netmask 0xffffff00 broadcast 192.168.178.255
media: autoselect
status: active
然后使用inet地址。这可以让我连接机器上的任何端口。
我们发现,对于所有这些网络垃圾,一个更简单的解决方案是仅为服务使用域套接字。如果您无论如何都试图连接到主机,只需将套接字作为卷挂载,就可以了。对于postgresql,这很简单:
docker run -v /var/run/postgresql:/var/run/postgresql
然后,我们只需设置数据库连接以使用套接字而不是网络。就是这么简单。
您可以通过两种方式访问运行在主机上的本地web服务器。
使用公网IP的方法1 使用主机公网IP地址访问Jenkins docker容器中的webserver。 与主机网络的方法2 使用"——net host"将Jenkins docker容器添加到主机的网络堆栈上。部署在主机堆栈上的容器具有对主机接口的全部访问权。您可以使用主机的私有IP地址访问docker容器中的本地web服务器。
NETWORK ID NAME DRIVER SCOPE
b3554ea51ca3 bridge bridge local
2f0d6d6fdd88 host host local
b9c2a4bc23b2 none null local
启动带有主机网络的容器 例如:docker运行——net host -it ubuntu并运行ifconfig来列出所有可从docker容器访问的可用网络IP地址。
我在我的本地主机上启动了一个nginx服务器,我能够从Ubuntu docker容器访问nginx网站的url。
Docker运行——net主机- ubuntu
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a604f7af5e36 ubuntu "/bin/bash" 22 seconds ago Up 20 seconds ubuntu_server
使用私有网络IP地址从Ubuntu docker容器访问Nginx web服务器(运行在本地主机上)。
root@linuxkit-025000000001:/# curl 192.168.x.x -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 05:12:12 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes