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

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


当前回答

执行:

docker ps -a

这将显示活动的docker图像:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                       PORTS               NAMES
3b733ae18c1c        parzee/database     "/usr/lib/postgresql/"   6 minutes ago       Up 6 minutes                 5432/tcp            serene_babbage

使用CONTAINER ID值:

docker inspect <CONTAINER ID> | grep -w "IPAddress" | awk '{ print $2 }' | head -n 1 | cut -d "," -f1

"172.17.0.2"

其他回答

为了扩展ko-dos的答案,这里有一个别名来列出所有容器名称及其IP地址:

alias docker-ips='docker ps | tail -n +2 | while read -a a; do name=${a[$((${#a[@]}-1))]}; echo -ne "$name\t"; docker inspect $name | grep IPAddress | cut -d \" -f 4; done'

仅为完整起见:

我真的很喜欢--format选项,但一开始我不知道它,所以我使用了一个简单的Python单行程序来获得相同的结果:

docker inspect <CONTAINER> |python -c 'import json,sys;obj=json.load(sys.stdin);print obj[0]["NetworkSettings"]["IPAddress"]'

Use:

docker inspect $CID | grep IPAddress | grep -v null| cut -d '"' -f 4 | head -1

Linux容器

.方法1

 docker exec postgres ifconfig

.方法2

  docker exec postgres cat /etc/hosts

.方法3

码头管理人员

.方法4

使用Powershell

docker inspect postgres | select-string 'ipaddress'

此脚本将获取所有正在运行的容器的IPv4地址,而无需进一步处理或解释结果。如果您也不想要容器名称,只需删除“echo-n$name:”行即可。非常适合自动化或填充变量。

#!/bin/sh
for NAME in $(docker ps --format {{.Names}})
do
  echo -n "$NAME:"
  docker inspect $NAME | grep -i "ip.*[12]*\.[0-9]*" | \
         sed -e 's/^  *//g' -e 's/[",]//g' -e 's/[a-zA-Z: ]//g'
done

如果需要,也可以创建别名:

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