如何从docker容器访问主机端口 [英] How to access host port from docker container
问题描述
编辑:我正在运行docker在Linux机器上。
更新:
除了下面的@larsks答案之外,要获取IP地址的主机IP,我做以下:
ip addr show docker0 | grep -Po'inet \K [\d。] +'
在Linux上本机运行Docker时,您可以使用 docker0
接口的IP地址访问主机服务。从容器内部,这将是您的默认路线。
例如,在我的系统上:
$ ip addr show docker0
7:docker0:< NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link / ether 00:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17 .255.255范围全局docker0
valid_lft永远preferred_lft永远
inet6 fe80 :: f4d2:49ff:fedd:28a0 / 64范围链接
valid_lft永远preferred_lft永远
在容器内:
#ip路线显示
默认通过172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 src 172.17.0.4
使用简单的shell
脚本来提取此IP地址非常简单:
# !/ bin / sh
hostip = $(ip route show | awk'/ default / {print $ 3}')
echo $ hostip
您可能需要修改主机上的 iptables
规则,以允许
连接码头容器。这样的事情可以做
技巧:
#iptables -A INPUT -i docker0 -j ACCEPT
这将允许从Docker
容器访问主机上的任何端口。请注意:
-
iptables规则被排序,并且此规则可能或可能不会执行
正确的事情,具体取决于 -
您只能访问主机服务,(a)
聆听INADDR_ANY
(又名0.0.0.0),或者明确地是
在docker0
界面上收听
I have a docker container running jenkins. As part of the build process, I need to access a web server that is run locally on the host machine. Is there a way the host web server (which can be configured to run on a port) can be exposed to the jenkins container?
EDIT: I'm running docker natively on a Linux machine.
UPDATE:
In addition to @larsks answer below, to get the IP address of the Host IP from the host machine, I do the following:
ip addr show docker0 | grep -Po 'inet \K[\d.]+'
When running Docker natively on Linux, you can access host services using the IP address of the docker0
interface. From inside the container, this will be your default route.
For example, on my system:
$ ip addr show docker0
7: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
link/ether 00:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::f4d2:49ff:fedd:28a0/64 scope link
valid_lft forever preferred_lft forever
And inside a container:
# ip route show
default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 src 172.17.0.4
It's fairly easy to extract this IP address using a simple shell script:
#!/bin/sh
hostip=$(ip route show | awk '/default/ {print $3}')
echo $hostip
You may need to modify the iptables
rules on your host to permit
connections from Docker containers. Something like this will do the
trick:
# iptables -A INPUT -i docker0 -j ACCEPT
This would permit access to any ports on the host from Docker containers. Note that:
iptables rules are ordered, and this rule may or may not do the right thing depending on what other rules come before it.
you will only be able to access host services that are either (a) listening on
INADDR_ANY
(aka 0.0.0.0) or that are explicitly listening on thedocker0
interface.
这篇关于如何从docker容器访问主机端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!