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


当前回答

如果你想要真实IP地址(不是网桥IP),并且你有docker 18.03(或最新的),执行以下操作:

在镜像名为nginx的主机上运行bash(适用于Alpine Linux发行版):

 docker run -it nginx /bin/ash

然后在容器内运行

/ # nslookup host.docker.internal

Name:      host.docker.internal
Address 1: 192.168.65.2

192.168.65.2是主机的IP,而不是spinus接受的应答中的网桥IP。

我在这里使用host.docker.internal:

主机有一个不断变化的IP地址(如果没有网络访问,则没有)。从18.03开始,我们的建议是连接到特殊的DNS名称host.docker.internal,它将解析为主机使用的内部IP地址。这是为了开发目的,不能在Docker for Windows之外的生产环境中工作。

其他回答

试试这个:

docker run --rm -i --net=host alpine ifconfig

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

在终端上使用hostname -I命令

所以…如果你使用Rancher服务器运行你的容器,Rancher v1.6(不确定2.0是否有)容器可以访问http://rancher-metadata/,其中有很多有用的信息。

从容器内部可以在这里找到IP地址: curl http://rancher-metadata/latest/self/host/agent_ip

详情见: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/

在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'/.$//'`