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

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


当前回答

for containerId in $(sudo docker ps -a | cut -f1 -d' ' | grep -v CONTAINER); do
    echo " ContainerId - $containerId >>  $(sudo docker inspect --format '{{ .NetworkSettings.IPAddress }}' $containerId) "
done

其他回答

如果您想快速查看所有Docker IP地址,或者不键入实例名称,可以破解Docker ps命令,将其添加到~/.bashrc文件中:

function docker-ips() {
    docker ps | while read line; do
        if `echo $line | grep -q 'CONTAINER ID'`; then
            echo -e "IP ADDRESS\t$line"
        else
            CID=$(echo $line | awk '{print $1}');
            IP=$(docker inspect -f "{{ .NetworkSettings.IPAddress }}" $CID);
            printf "${IP}\t${line}\n"
        fi
    done;
}

这来自Andrew Johnstone在Docker GitHub上的提议:https://github.com/docker/docker/issues/8786

我用这个简单的方法

docker exec -it <container id or name> hostname -i

e.g

ubuntu@myhost:~$ docker exec -it 3d618ac670fe hostname -i
10.0.1.5

Linux容器

.方法1

 docker exec postgres ifconfig

.方法2

  docker exec postgres cat /etc/hosts

.方法3

码头管理人员

.方法4

使用Powershell

docker inspect postgres | select-string 'ipaddress'

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

plus

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

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

使用Python新API:

import docker

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