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


当前回答

我是这样做的。在这种情况下,它在docker镜像的/etc/hosts中添加了一个hosts条目,将taurus-host指向我的本地机器IP::

TAURUS_HOST=`ipconfig getifaddr en0`
docker run -it --rm -e MY_ENVIRONMENT='local' --add-host "taurus-host:${TAURUS_HOST}" ...

然后,从Docker容器中,脚本可以使用主机名taurus-host访问到承载Docker容器的本地机器。

其他回答

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"

我有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]

在linux中你可以运行

HOST_IP=`hostname -I | awk '{print $1}'`

在macOS中,您的主机不是Docker主机。Docker将在VirtualBox中安装它的主机操作系统。

HOST_IP=`docker run busybox ping -c 1 docker.for.mac.localhost | awk 'FNR==2 {print $4}' | sed s'/.$//'`

也许我创建的容器也很有用https://github.com/qoomon/docker-host

你可以简单地使用容器名称dns访问主机系统,例如curl http://dockerhost:9200,所以不需要任何IP地址的麻烦。

如果你启用了docker远程API(例如通过-Htcp://0.0.0.0:4243),并且知道主机的主机名或IP地址,这可以通过大量的bash来完成。

在容器的用户bashrc中:

export hostIP=$(ip r | awk '/default/{print $3}')
export containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
export proxyPort=$(
  curl -s http://$hostIP:4243/containers/$containerID/json |
  node -pe 'JSON.parse(require("fs").readFileSync("/dev/stdin").toString()).NetworkSettings.Ports["DESIRED_PORT/tcp"][0].HostPort'
)

第二行从本地/proc/self/cgroup文件中获取容器ID。

第三行卷曲到主机(假设您使用4243作为docker的端口),然后使用node解析返回的JSON为DESIRED_PORT。