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


当前回答

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"

其他回答

所以…如果你使用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/

与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

在Ubuntu上,hostname命令可以与以下选项一起使用:

-i,——ip-address主机名地址 -I,——all-ip-addresses主机的所有地址

例如:

$ hostname -i
172.17.0.2

要给变量赋值,可以使用以下一行代码:

IP=$(hostname -i)

下面是在AWS中运行Docker的另一个选择。这个选项避免了使用apk来添加curl包,节省了宝贵的7mb空间。使用内置的wget (BusyBox二进制文件的一部分):

wget -q -O - http://169.254.169.254/latest/meta-data/local-ipv4

唯一的方法是在创建容器时将主机信息作为环境传递

run --env <key>=<value>