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

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


当前回答

对于那些从谷歌来寻找从终端执行命令的解决方案(而不是通过脚本)的人来说,“jid”是一个交互式JSON向下钻取实用程序,具有自动完成和建议功能,它可以让你用更少的键入来做同样的事。

docker inspect $CID | jid

键入Tab.Net Tab,您将看到类似的内容:

[Filter]> .[0].NetworkSettings
{
  "Bridge": "",
  "EndpointID": "b69eb8bd4f11d8b172c82f21ab2e501fe532e4997fc007ed1a997750396355d5",
  "Gateway": "172.17.0.1",
  "GlobalIPv6Address": "",
  "GlobalIPv6PrefixLen": 0,
  "HairpinMode": false,
  "IPAddress": "172.17.0.2",
  "IPPrefixLen": 16,
  "IPv6Gateway": "",
  "LinkLocalIPv6Address": "",
  "LinkLocalIPv6PrefixLen": 0,
  "MacAddress": "02:42:ac:11:00:02",
  "Networks": {
    "bridge": {
      "Aliases": null,
      "EndpointID": "b69eb8bd4f11d8b172c82f21ab2e501fe532e4997fc007ed1a997750396355d5",
      "Gateway": "172.17.0.1",
      "GlobalIPv6Address": "",

键入.IPA选项卡,您将看到类似的内容:

[Filter]> .[0].NetworkSettings.IPAddress
"172.17.0.2"

其他回答

使用Python新API:

import docker

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

Inspect对我不起作用。可能是因为我使用了-net主机和一些名称空间。

总之,我发现这很有效:

docker exec -i -t NAME /sbin/ifconfig docker0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

按名称引用容器:

docker run ... --name pg-master

然后按名称获取IP地址:

MASTER_HOST=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' pg-master)

我的多网络环境有问题,所以这是一个更动态的版本

获取驻留在一个合成文件中的所有主机名、网络和IP

 for N in $(docker-compose ps -q) ; do echo "$(docker inspect -f '{{.Config.Hostname}}' ${N}) $(docker inspect -f '{{range $i, $value := .NetworkSettings.Networks}} [{{$i}}:{{.IPAddress}}]{{end}}' ${N})"; done

输出

containerA [networkA:192.168.1.4] [networkB:192.168.2.4]
containerB  [networkA:192.168.1.5]

要获取所有正在运行的容器,请替换第一个命令

for N in $(docker-compose ps -q)

with

 for N in $(docker container ls | awk 'NR>=2' | cut -c1-12 );

获取给定1个特定网络的1个特定容器(具有多个网络)的IP

docker inspect --format='{{range $i, $value := .NetworkSettings.Networks}}{{if eq $i "NETWORKNAME"}}{{.IPAddress}}{{end}}{{end}}' CONTAINERNAME

输出

192.168.1.4

获取给定1个特定网络的所有容器(具有多个网络)的“主机名IP”

for N in $(docker-compose ps -q) ; do echo "$(docker inspect -f '{{.Config.Hostname}}' ${N}) $(docker inspect -f '{{range $i, $value := .NetworkSettings.Networks}}{{if eq $i "intranet"}}{{.IPAddress}}{{end}}{{end}}' ${N})"; done

输出

containerA 192.168.1.4
containerB 192.168.1.5

获取给定1个特定网络的所有容器(具有多个网络)的IP

for N in $(docker-compose ps -q) ; do echo " $(docker inspect -f '{{range $i, $value := .NetworkSettings.Networks}}{{if eq $i "intranet"}}{{.IPAddress}}{{end}}{{end}}' ${N})"; done

输出

192.168.1.4
192.168.1.5

这是我今天用Python开发的一个解决方案,使用docker inspect容器JSON输出作为数据源。

我有很多容器和基础设施需要检查,我需要从任何容器中以快速、漂亮的方式获取基本的网络信息。这就是我写这个剧本的原因。

重要提示:从1.9版开始,Docker允许您创建多个网络并将它们连接到容器。

#!/usr/bin/python

import json
import subprocess
import sys

try:
    CONTAINER = sys.argv[1]
except Exception as e:
    print "\n\tSpecify the container name, please."
    print "\t\tEx.:  script.py my_container\n"
    sys.exit(1)

# Inspecting container via Subprocess
proc = subprocess.Popen(["docker","inspect",CONTAINER],
                      stdout=subprocess.PIPE,
                      stderr=subprocess.STDOUT)

out = proc.stdout.read()
json_data = json.loads(out)[0]

net_dict = {}
for network in json_data["NetworkSettings"]["Networks"].keys():
    net_dict['mac_addr']  = json_data["NetworkSettings"]["Networks"][network]["MacAddress"]
    net_dict['ipv4_addr'] = json_data["NetworkSettings"]["Networks"][network]["IPAddress"]
    net_dict['ipv4_net']  = json_data["NetworkSettings"]["Networks"][network]["IPPrefixLen"]
    net_dict['ipv4_gtw']  = json_data["NetworkSettings"]["Networks"][network]["Gateway"]
    net_dict['ipv6_addr'] = json_data["NetworkSettings"]["Networks"][network]["GlobalIPv6Address"]
    net_dict['ipv6_net']  = json_data["NetworkSettings"]["Networks"][network]["GlobalIPv6PrefixLen"]
    net_dict['ipv6_gtw']  = json_data["NetworkSettings"]["Networks"][network]["IPv6Gateway"]
    for item in net_dict:
        if net_dict[item] == "" or net_dict[item] == 0:
            net_dict[item] = "null"
    print "\n[%s]" % network
    print "\n{}{:>13} {:>14}".format(net_dict['mac_addr'],"IP/NETWORK","GATEWAY")
    print "--------------------------------------------"
    print "IPv4 settings:{:>16}/{:<5}  {}".format(net_dict['ipv4_addr'],net_dict['ipv4_net'],net_dict['ipv4_gtw'])
    print "IPv6 settings:{:>16}/{:<5}  {}".format(net_dict['ipv6_addr'],net_dict['ipv6_net'],net_dict['ipv6_gtw'])

输出为:

$ python docker_netinfo.py debian1

[frontend]

02:42:ac:12:00:02   IP/NETWORK        GATEWAY
--------------------------------------------
IPv4 settings:      172.18.0.2/16     172.18.0.1
IPv6 settings:            null/null   null

[backend]

02:42:ac:13:00:02   IP/NETWORK        GATEWAY
--------------------------------------------
IPv4 settings:      172.19.0.2/16     172.19.0.1
IPv6 settings:            null/null   null