正如标题所示,我需要能够检索docker托管的IP地址以及从主机到容器的portmap,并在容器内部完成这些工作。


当前回答

我有Ubuntu 16.03。对我来说

docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print  $3}'` [image]

不工作(错误的ip正在生成)

我的解决方案是:

docker run --add-host dockerhost:`docker network inspect --format='{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge` [image]

其他回答

与https://docs.docker.com/machine/install-machine/

A) $ docker-machine IP

b)获取一台或多台机器的IP地址。

  $ docker-machine ip host_name

  $ docker-machine ip host_name1 host_name2

——add-host可能是一个更简洁的解决方案(但没有端口部分,只能使用该解决方案处理主机)。所以,在你的docker运行命令中,做如下的事情:

docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print  $3}'` [my container]

(来自https://stackoverflow.com/a/26864854/127400)

/sbin/ip route|awk '/default/ { print $3 }'

正如@MichaelNeale注意到的,在Dockerfile中使用这个方法是没有意义的(除非我们只在构建时需要这个IP),因为这个IP在构建时是硬编码的。

AFAIK,在Docker for Linux(标准发行版)的情况下,主机的IP地址将始终是172.17.0.1(在Docker的主网络上,请参阅评论了解更多)。

最简单的方法是从主机上通过ifconfig(接口docker0)获取:

ifconfig

在docker内部,docker可以执行以下命令:ip -4 route show default | cut -d" " -f3

你可以用下面的命令行在docker中快速运行它:

# 1. Run an ubuntu docker
# 2. Updates dependencies (quietly)
# 3. Install ip package   (quietly)
# 4. Shows (nicely) the ip of the host
# 5. Removes the docker (thanks to `--rm` arg)
docker run -it --rm ubuntu:22.04 bash -c "apt-get update > /dev/null && apt-get install iproute2 -y > /dev/null && ip -4 route show default | cut -d' ' -f3"

我的解决方案:

Docker运行——net=host

然后在docker容器中:

hostname -I | awk '{打印$1}'