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

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


当前回答

如果您需要一个特定的方便别名来获取特定的容器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'

其他回答

注意!!!Docker Compose用法:

由于Docker Compose为每个集群创建了一个独立的网络,因此下面的方法不适用于Docker Compos。


最优雅和简单的方法是定义一个shell函数,这是目前投票最多的@WouterD答案:

dockip() {
  docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$@"
}

Docker可以像Linux程序一样将容器ID写入文件:

使用--cidfile=filename运行时,Docker将容器的ID转储为“filename”。

有关更多信息,请参阅“Docker运行PID等效部分”。

--cidfile="app.cid": Write the container ID to the file

使用PID文件:

运行带有--cidfile参数的容器时,app.cid文件内容如下:2009年12月29日您可以使用文件内容检查Docker容器:blog-v4git:(开发)✗ docker inspect `cat app.cid`您可以使用内联Python脚本提取容器IP:$docker inspect `cat app.cid` | python-c“import json;import sys\sys.stdout.write(json.load(sys.stdin)[0]['NetworkSettings']['IPAddress'])“172.17.0.2

这是一种更人性化的形式:

#!/usr/bin/env python
# Coding: utf-8
# Save this file like get-docker-ip.py in a folder that in $PATH
# Run it with
# $ docker inspect <CONTAINER ID> | get-docker-ip.py

import json
import sys

sys.stdout.write(json.load(sys.stdin)[0]['NetworkSettings']['IPAddress'])

有关更多信息,请参阅“获取Docker容器IP地址的10种选择”。

如果您忘记了容器ID或不想使用shell命令进行操作,最好使用像Portiner这样的UI。

https://portainer.io/

$ docker volume create portainer_data
$ docker run -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer

在那里,您可以找到有关容器的所有信息以及IP。

我必须通过docker容器名称提取docker容器IP地址,以便在部署脚本中进一步使用。为此,我编写了以下bash命令:

docker inspect $(sudo docker ps | grep my_container_name | head -c 12) | grep -e \"IPAddress\"\:[[:space:]]\"[0-2] | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'

假设将其放置到bash脚本中会很方便,该脚本会期望my_container_name作为参数。。。

检查此脚本:https://github.com/jakubthedeveloper/DockerIps

它以以下格式返回容器名称及其IP:

abc_nginx 172.21.0.4
abc_php 172.21.0.5
abc_phpmyadmin 172.21.0.3
abc_mysql 172.21.0.2

如果您想快速查看所有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