创建新容器后,是否可以运行命令从主机获取容器的IP地址?

基本上,一旦Docker创建了容器,我就想滚动我自己的代码部署和容器配置脚本。


当前回答

只是另一个经典的解决方案:

docker ps -aq | xargs docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}'

其他回答

使用Python新API:

import docker

client = docker.DockerClient()
container = client.containers.get("NAME")
ip_add = container.attrs['NetworkSettings']['IPAddress']
print(ip_add)

码头工人检查MY_CONTAINER | jq-r'。[].网络设置.网络[].IP地址'

plus

优雅的语法灵活(一旦你使用jq,你可以在任何地方使用它,有json,非常有用)强大的

需要安装jq(例如apt-get-installjq)

有多种方法可以从主机获取容器的IP

docker inspect-f“{{range.NetworkSettings.Networks}}{{.IPAddress}}}{{end}”containerID

如果您记不住上面的命令,您可以始终执行以下操作

码头工人检查集装箱ID

它将在返回信息后返回Docker对象的低级信息。查找“网络”,然后在其中找到容器的“IPAddress”

如果您需要一个特定的方便别名来获取特定的容器ip,请使用此别名,并提供公认的答案

alias dockerip='f(){ docker inspect $1|grep -i "ipaddress.*[12]*\.[0-9]*"|sed -e "s/^  *//g" -e "s/[\",]//g" -e "s/[*,]//g" -e "s/[a-zA-Z: ]//g" | sort --unique;  unset -f f; }; f'

然后你可以用

dockerip <containername>  

您也可以使用contained而不是containername

BTW接受了很好的答案,但没有产生干净的输出,所以我编辑了它,并这样使用;

alias dockerips='for NAME in $(docker ps --format {{.Names}}); do echo -n "$NAME:"; docker inspect $NAME|grep -i "ipaddress.*[12]*\.[0-9]*"|sed -e "s/^  *//g" -e "s/[\",]//g" -e "s/[_=*,]//g" -e "s/[a-zA-Z: ]//g "| sort --unique;done'

要获取容器的IP地址和主机端口,请执行以下操作:

docker inspect containerId | awk '/IPAddress/ || /HostPort/'

输出:

    "HostPort": "4200"
                    "HostPort": "4200"
        "SecondaryIPAddresses": null,
        "IPAddress": "172.17.0.2",
                "IPAddress": "172.17.0.2",