简体   繁体   English

如何从主机获取 Docker 容器的 IP 地址

[英]How to get a Docker container's IP address from the host

Is there a command I can run to get the container's IP address right from the host after a new container is created?创建新容器后,是否可以运行命令从主机获取容器的 IP 地址?

Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.基本上,一旦 Docker 创建了容器,我就想滚动我自己的代码部署和容器配置脚本。

The --format option of inspect comes to the rescue. inspect--format选项可以解决问题。

Modern Docker client syntax is:现代 Docker 客户端语法是:

docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id

Old Docker client syntax is:旧的 Docker 客户端语法是:

docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id

These commands will return the Docker container's IP address.这些命令将返回 Docker 容器的 IP 地址。

As mentioned in the comments: if you are on Windows, use double quotes " instead of single quotes ' around the curly braces.如评论中所述:如果您使用的是 Windows,请在大括号周围使用双引号"而不是单引号'

You can use docker inspect <container id> .您可以使用docker inspect <container id>

For example:例如:

CID=$(docker run -d -p 4321 base nc -lk 4321);
docker inspect $CID

First get the container ID:首先获取容器ID:

docker ps

(First column is for container ID) (第一列是容器 ID)

Use the container ID to run:使用容器 ID 运行:

docker inspect <container ID>

At the bottom,under "NetworkSettings", you can find "IPAddress"在底部的“网络设置”下,您可以找到“IP地址”

Or Just do:或者只是这样做:

docker inspect <container id> | grep "IPAddress"
docker inspect CONTAINER_ID | grep "IPAddress"

您可以将-i添加到 grep 以忽略大小写,那么即使以下内容也可以工作:

docker inspect CONTAINER_ID | grep -i "IPaDDreSS"

To get all container names and their IP addresses in just one single command.只需一个命令即可获取所有容器名称及其 IP 地址。

docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}' $(docker ps -aq)

If you are using docker-compose the command will be this:如果您正在使用docker-compose命令将是这样的:

docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)

The output will be:输出将是:

/containerA - 172.17.0.4
/containerB - 172.17.0.3
/containerC - 172.17.0.2

Add this shell script in your ~/.bashrc or relevant file:在你的~/.bashrc或相关文件中添加这个 shell 脚本:

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

Then, to get an IP address of a container, simply do this:然后,要获取容器的 IP 地址,只需执行以下操作:

docker-ip YOUR_CONTAINER_ID

For the new version of the Docker, please use the following:对于新版本的 Docker,请使用以下内容:

docker-ip() {
        docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$@"
}

In Docker 1.3+, you can also check it using:在 Docker 1.3+ 中,您还可以使用以下方法进行检查:

Enter the running Docker (Linux):进入正在运行的 Docker (Linux):

docker exec [container-id or container-name] cat /etc/hosts
172.17.0.26 d8bc98fa4088
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.17 mysql

For windows:对于窗户:

docker exec [container-id or container-name] ipconfig

显示所有容器的 IP 地址:

docker inspect --format='{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)

As of Docker version 1.10.3, build 20f81dd从 Docker 版本 1.10.3 开始,构建 20f81dd

Unless you told Docker otherwise, Docker always launches your containers in the bridge network.除非你另外告诉 Docker,否则 Docker 总是在桥接网络中启动你的容器。 So you can try this command below:所以你可以试试下面的这个命令:

docker network inspect bridge

Which should then return a Containers section which will display the IP address for that running container.然后应该返回一个 Containers 部分,该部分将显示该正在运行的容器的 IP 地址。

[
    {
        "Name": "bridge",
        "Id": "40561e7d29a08b2eb81fe7b02736f44da6c0daae54ca3486f75bfa81c83507a0",
        "Scope": "local",
        "Driver": "bridge",
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16"
                }
            ]
        },
        "Containers": {
            "025d191991083e21761eb5a56729f61d7c5612a520269e548d0136e084ecd32a": {
                "Name": "drunk_leavitt",
                "EndpointID": "9f6f630a1743bd9184f30b37795590f13d87299fe39c8969294c8a353a8c97b3",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        }
    }
]

Execute:执行:

docker ps -a

This will display active docker images:这将显示活动的泊坞窗图像:

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

Use the CONTAINER ID value:使用容器 ID 值:

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

"172.17.0.2" “172.17.0.2”

Based on some of the answers I loved, I decided to merge them to a function to get all the IP addresses and another for an specific container.根据我喜欢的一些答案,我决定将它们合并到一个函数中以获取所有 IP 地址,并为特定容器获取另一个。 They are now in my .bashrc file.它们现在在我的.bashrc文件中。

docker-ips() {
    docker inspect --format='{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
}

docker-ip() {
  docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$@"
}

The first command gives the IP address of all the containers and the second a specific container's IP address.第一个命令给出所有容器的 IP 地址,第二个命令给出特定容器的 IP 地址。

docker-ips
docker-ip YOUR_CONTAINER_ID

Here's a quick working answer:这是一个快速的工作答案:

Get your container name or ID:获取您的容器名称或 ID:

docker container ls

Then get the IP:然后获取IP:

docker inspect <container_ID Or container_name> |grep 'IPAddress'

Get the port:获取端口:

docker inspect <container_ID Or container_name> |grep 'Port'

My answer:我的答案:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} %tab% {{.Name}}' $(docker ps -aq
) | sed 's#%tab%#\t#g' | sed 's#/##g' | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n

Also as a bash alias:也作为 bash 别名:

docker-ips() {   docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} %tab% {{.Name}}' $(docker ps -aq) | sed 's#%tab%#\t#g' | sed 's#/##g' | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n }

Output is sorted by IP address, and tab delimited:输出按 IP 地址排序,并以制表符分隔:

# docker-ips
172.18.0.2       memcached
172.18.0.3       nginx
172.18.0.4       fpm-backup
172.18.0.5       dns
172.18.0.6       fpm-beta
172.18.0.7       exim
172.18.0.8       fpm-delta
172.18.0.9       mariadb
172.18.0.10      fpm-alpha
172.19.0.2       nextcloud-redis
172.19.0.3       nextcloud-db
172.19.0.4       nextcloud

I wrote the following Bash script to get a table of IP addresses from all containers running under docker-compose .我编写了以下 Bash 脚本来从docker-compose下运行的所有容器获取 IP 地址表。

function docker_container_names() {
    docker ps -a --format "{{.Names}}" | xargs
}

# Get the IP address of a particular container
dip() {
    local network
    network='YOUR-NETWORK-HERE'
    docker inspect --format "{{ .NetworkSettings.Networks.$network.IPAddress }}" "$@"
}

dipall() {
    for container_name in $(docker_container_names);
    do
        local container_ip=$(dip $container_name)
        if [[ -n "$container_ip" ]]; then
            echo $(dip $container_name) " $container_name"
        fi
    done | sort -t . -k 3,3n -k 4,4n
}

You should change the variable network to your own network name.您应该将变量 network 更改为您自己的网络名称。

Docker is written in Go and it uses Go syntax for query purposes too. Docker 是用 Go 编写的,它也使用 Go 语法进行查询。

To inspect the IP address of a particular container, you need to run the command ( -f for "format"):要检查特定容器的 IP 地址,您需要运行命令( -f表示“格式”):

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_id_or_name

For the container ID or name, you can run the command对于容器 ID 或名称,您可以运行命令

docker container ls

which will list every running container.这将列出每个正在运行的容器。

Reference containers by name:按名称引用容器:

docker run ... --name pg-master

Then grab the IP address address by name:然后按名称抓取IP地址:

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

Here's is a solution that I developed today in Python, using the docker inspect container JSON output as the data source.这是我今天用 Python 开发的一个解决方案,使用docker inspect container JSON 输出作为数据源。

I have a lot of containers and infrastructures that I have to inspect, and I need to obtain basic network information from any container, in a fast and pretty manner.我有很多容器和基础设施需要检查,我需要从任何容器中以快速和漂亮的方式获取基本网络信息。 That's why I made this script.这就是我制作这个脚本的原因。

IMPORTANT: Since the version 1.9, Docker allows you to create multiple networks and attach them to the containers.重要提示:从 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'])

The output is:输出是:

$ 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

I use this simple way我用这个简单的方法

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

eg例如

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

为了扩展 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'

NOTE!!!笔记!!! for Docker Compose Usage:对于 Docker Compose 用法:

Since Docker Compose creates an isolated network for each cluster, the methods below do not work with docker-compose .由于 Docker Compose 为每个集群创建了一个隔离的网络,因此以下方法不适用于docker-compose


The most elegant and easy way is defining a shell function, currently the most-voted answer @WouterD's :最优雅、最简单的方法是定义一个 shell 函数,这是目前投票最多的答案@WouterD

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

Docker can write container IDs to a file like Linux programs: Docker 可以像 Linux 程序一样将容器 ID 写入文件:

Running with --cidfile=filename , Docker dumps the ID of the container to "filename".使用--cidfile=filename运行,Docker 将容器的 ID 转储到“文件名”。

See " Docker runs PID equivalent Section " for more information.有关更多信息,请参阅“ Docker 运行 PID 等效部分”。

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

Using a PID file:使用PID文件:

  1. Running container with --cidfile parameter, the app.cid file content is like:使用--cidfile参数运行容器, app.cid文件内容如下:

     a29ac3b9f8aebf66a1ba5989186bd620ea66f1740e9fe6524351e7ace139b909
  2. You can use file content to inspect Docker containers:您可以使用文件内容来检查 Docker 容器:

     blog-v4 git:(develop) ✗ docker inspect `cat app.cid`
  3. You can extract the container IP using an inline Python script:您可以使用内联 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

Here's a more human friendly form:这是一种更人性化的形式:

#!/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'])

See " 10 alternatives of getting the Docker container IP addresses " for more information.有关更多信息,请参阅“ 获取 Docker 容器 IP 地址的 10 种方法”。

docker inspect --format '{{ .NetworkSettings.IPAddress }}' <containername or containerID here>

The above works if the container is deployed to the default bridge network.如果容器部署到默认网桥网络,则上述方法有效。

However, if using a custom bridge network or a overlay network, I found the below to work better:但是,如果使用自定义桥接网络或覆盖网络,我发现以下方法效果更好:

docker exec <containername or containerID here> /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

将之前的答案与根据 Docker 映像名称查找容器 ID 相结合:

docker inspect --format '{{ .NetworkSettings.IPAddress }}' `docker ps | grep $IMAGE_NAME | sed 's/\|/ /' | awk '{print $1}'`

Just for completeness:只是为了完整性:

I really like the --format option, but at first I wasn't aware of it so I used a simple Python one-liner to get the same result:我真的很喜欢--format选项,但一开始我并不知道它,所以我使用了一个简单的 Python one-liner 来获得相同的结果:

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

If you installed Docker using Docker Toolbox, you can use the Kitematic application to get the container IP address:如果您使用 Docker Toolbox 安装 Docker,则可以使用 Kitematic 应用程序获取容器 IP 地址:

  1. Select the container选择容器
  2. Click on Settings点击设置
  3. Click in Ports tab.单击端口选项卡。

To get the IP address and host port of a container:获取容器的 IP 地址和主机端口:

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

Output:输出:

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

For those who came from Google to find a solution for command execution from the terminal (not by a script), " jid ", which is an interactive JSON drill-down utility with autocomplete and suggestion, lets you do the same thing with less typing.对于那些从 Google 来寻找从终端(而不是通过脚本)执行命令的解决方案的人来说,“ jid ”是一个具有自动完成和建议的交互式 JSON 向下钻取实用程序,可让您以更少的输入完成同样的事情.

docker inspect $CID | jid

Type Tab .Net Tab and you'll see something like:输入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": "",

Type .IPA Tab and you'll see something like: .IPA Tab ,你会看到类似的内容:

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

对于 Windows 10:

docker inspect --format "{{ .NetworkSettings.IPAddress }}"  containerId

这将列出主机上的所有容器 IP:

sudo docker ps -aq | while read line;  do sudo docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $line ; done

The accepted answer does not work well with multiple networks per container:接受的答案不适用于每个容器的多个网络:

> docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' cc54d96d63ea

172.20.0.4172.18.0.5

The next best answer is closer:下一个最佳答案更接近:

> docker inspect cc54d96d63ea | grep "IPAddress"

"SecondaryIPAddresses": null,
"IPAddress": "",
    "IPAddress": "172.20.0.4",
    "IPAddress": "172.18.0.5",

I like to use jq to parse the network JSON:我喜欢用jq来解析网络JSON:

> docker inspect cc54d96d63ea | jq -r 'map(.NetworkSettings.Networks) []'

{
  "proxy": {
    "IPAMConfig": null,
    "Links": [
      "server1_php_1:php",
      "server1_php_1:php_1",
      "server1_php_1:server1_php_1"
    ],
    "Aliases": [
      "cc54d96d63ea",
      "web"
    ],
    "NetworkID": "7779959d7383e9cef09c970c38c24a1a6ff44695178d314e3cb646bfa30d9935",
    "EndpointID": "4ac2c26113bf10715048579dd77304008904186d9679cdbc8fcea65eee0bf13b",
    "Gateway": "172.20.0.1",
    "IPAddress": "172.20.0.4",
    "IPPrefixLen": 24,
    "IPv6Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "MacAddress": "02:42:ac:14:00:04",
    "DriverOpts": null
  },
  "webservers": {
    "IPAMConfig": null,
    "Links": [
      "server1_php_1:php",
      "server1_php_1:php_1",
      "server1_php_1:server1_php_1"
    ],
    "Aliases": [
      "cc54d96d63ea",
      "web"
    ],
    "NetworkID": "907a7fba8816cd0ad89b7f5603bbc91122a2dd99902b504be6af16427c11a0a6",
    "EndpointID": "7febabe380d040b96b4e795417ba0954a103ac3fd37e9f6110189d9de92fbdae",
    "Gateway": "172.18.0.1",
    "IPAddress": "172.18.0.5",
    "IPPrefixLen": 24,
    "IPv6Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "MacAddress": "02:42:ac:12:00:05",
    "DriverOpts": null
  }
}

To list the IP addresses of every container then becomes:要列出每个容器的 IP 地址,则变为:

for s in `docker ps -q`; do
  echo `docker inspect -f "{{.Name}}" ${s}`:
  docker inspect ${s} | jq -r 'map(.NetworkSettings.Networks) []' | grep "IPAddress";
done

/server1_web_1:
    "IPAddress": "172.20.0.4",
    "IPAddress": "172.18.0.5",
/server1_php_1:
    "IPAddress": "172.20.0.3",
    "IPAddress": "172.18.0.4",
/docker-gen:
    "IPAddress": "172.18.0.3",
/nginx-proxy:
    "IPAddress": "172.20.0.2",
    "IPAddress": "172.18.0.2",

Docker检查用于打印所有容器ips及其各自的名称

docker ps -q | xargs -n 1 docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} {{ .Name }}' | sed 's/ \// /'

Is there a command I can run to get the container's IP address right from the host after a new container is created?创建新容器后,是否可以运行命令从主机获取容器的IP地址?

Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.基本上,一旦Docker创建了容器,我就想推出自己的代码部署和容器配置脚本。

For Windows containers use 对于Windows容器使用

docker exec <container> ipconfig

where <container> is the name or the id of the container. 其中<container><container>名称ID

You can use docker ps to find the id of the container. 您可以使用docker ps查找容器的ID。

If you forgot container ID or don't want to manipulate with shell commands, it's better to use UI like Portainer. 如果您忘记了容器ID或不想使用shell命令进行操作,最好使用类似于Portainer的UI。

https://portainer.io/ 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

There you can find all information about container also IP. 在这里,您可以找到有关容器以及IP的所有信息。

Nobody has proposed the Docker Python API yet.还没有人提出 Docker Python API。 Docker API solution to get IP Address is fairly simple.获取 IP 地址的 Docker API 解决方案相当简单。

*NIX based OS: docker api 3.7 (updated thanks to canadadry from the comments) *基于 NIX 的操作系统: docker api 3.7(感谢评论中的canadadry更新)

import docker

client = docker.DockerClient(base_url='unix://var/run/docker.sock')
x_container = client.containers(filters={"name":"x_container"})[0]
x_ip_addr = x_container["NetworkSettings"]["Networks"]["NETWORK_NAME"]["IPAddress"]

OS Agnostic: docker api 4.0.x (added thanks to pds from the comments)操作系统无关: docker api 4.0.x(感谢评论中的pds添加)

import docker

client = docker.from_env()
container = client.containers.get(container_name)
vars( container )["attrs"]["NetworkSettings"]["Networks"]["<NETWORK_NAME>"]["IPAddress"]

Wasn't too hard to find, but is useful.不是太难找,但很有用。 additionally this can be easily modified to find all IP's assigned to a container on various networks.此外,这可以轻松修改以查找分配给各种网络上容器的所有 IP。

Inspect didn't work for me.检查对我不起作用。 Maybe as I was using -net host and some namespaces.也许当我使用-net host和一些命名空间时。

Anyway, I found this to work nicely:无论如何,我发现这很好用:

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

I had to extract docker container IP Adress by docker container name for further usage in deployment scripts.我必须通过 docker 容器名称提取 docker 容器 IP 地址,以便在部署脚本中进一步使用。 For this purpose I have written the following bash command:为此,我编写了以下 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\}'
docker inspect <container id> | grep -i ip

例如:

docker inspect 2b0c4b617a8c | grep -i ip

This script will get the IPv4 address for all running containers without further processing or interpreting results.此脚本将获取所有正在运行的容器的 IPv4 地址,而无需进一步处理或解释结果。 If you don't want the container name as well, you can just remove the "echo -n $NAME:" line.如果您也不需要容器名称,则可以删除“echo -n $NAME:”行。 Great for automation or filling variables.非常适合自动化或填充变量。

#!/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

you can just create an alias too if you wanted like this:如果你想要这样的话,你也可以创建一个别名:

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"'

I had troubles with my multi-network environment so this is a more dynamic version<\/em>我的多网络环境有问题,所以这是一个更动态的版本<\/em>

Get all hostnames, networks and IPs residing in one compose file获取驻留在一个撰写文件中的所有主机名、网络和 IP<\/h2>
 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<\/code><\/pre>

Outputs<\/em>输出<\/em>

containerA [networkA:192.168.1.4] [networkB:192.168.2.4] containerB [networkA:192.168.1.5]<\/code><\/pre>

To get all running containers replace the first command要获取所有正在运行的容器,请替换第一个命令

for N in $(docker-compose ps -q)<\/code><\/pre>

with

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

Get IP of 1 specific container (with multiple networks), given 1 specific network给定 1 个特定网络,获取 1 个特定容器(具有多个网络)的 IP<\/h2>
 docker inspect --format='{{range $i, $value := .NetworkSettings.Networks}}{{if eq $i "NETWORKNAME"}}{{.IPAddress}}{{end}}{{end}}' CONTAINERNAME<\/code><\/pre>

Outputs<\/em>输出<\/em>

192.168.1.4<\/code><\/pre>

Get 'Hostname IP' of all containers (with multiple networks), given 1 specific network给定 1 个特定网络,获取所有容器(具有多个网络)的“主机名 IP”<\/h2>
 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<\/code><\/pre>

Outputs<\/em>输出<\/em>

containerA 192.168.1.4 containerB 192.168.1.5<\/code><\/pre>

Get IP of all containers (with multiple networks), given 1 specific network给定 1 个特定网络,获取所有容器(具有多个网络)的 IP<\/h2>
 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<\/code><\/pre>

Outputs<\/em>输出<\/em>

192.168.1.4 192.168.1.5<\/code><\/pre>"

在 Windows PowerShell 中尝试:

     docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" <container id>

The accepted answer covers exactly what to type fairly well, but here's a minor improvement:接受的答案准确地涵盖了要输入的内容,但这里有一个小的改进:

docker container inspect \
  --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' \
  $container_id_or_name

This uses the docker container inspect instead of the more generic docker inspect since docker is moving to a noun+verb syntax in their commands, and removing ambiguity of what you are inspecting.这使用docker container inspect而不是更通用的docker inspect ,因为 docker 在其命令中转向名词+动词语法,并消除了您正在检查的内容的歧义。 I've also included a space after the IP address since containers can be on more than one docker network with more than one IP address.我还在 IP 地址之后添加了一个空格,因为容器可以位于具有多个 IP 地址的多个 docker 网络上。 That could be swapped out for any other character or string that makes sense to you.可以将其换成对您有意义的任何其他字符或字符串。


For those that want to know how they can lookup other values, I often use the following to output any docker formatted syntax into json:对于那些想知道如何查找其他值的人,我经常使用以下命令将任何 docker 格式的语法输出到 json 中:

docker container inspect --format '{{json .}}' $container_id_or_name | jq .

You may need to install jq for this to work, or you can leave off the trailing command to read the json as a single long line.您可能需要安装jq才能使其正常工作,或者您可以省略尾随命令以将 json 读取为单个长行。 When viewing this output, you can see each key name and it's parents so you can create your own format strings to output anything you want.查看此输出时,您可以看到每个键名及其父项,因此您可以创建自己的格式字符串来输出您想要的任何内容。 The format syntax is implemented with golang's template with some extra docker specific functions included .格式语法是使用golang 的模板实现的,其中包含一些额外的 docker 特定功能


Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.基本上,一旦 Docker 创建了容器,我想滚动我自己的代码部署和容器配置脚本。

The main reason for my answer is this comment has a huge red flag to me.我回答的主要原因是这条评论对我来说是一个巨大的危险信号。 It indicates that your images do not contain everything needed to run your application, a big anti-pattern when working with containers.它表明您的图像不包含运行应用程序所需的所有内容,这在使用容器时是一个很大的反模式。 With a dozen clients over many years, I've yet to find a real world use case to connect directly to a container by it's internal IP address from the docker host that didn't have a better option.多年来有十几个客户,我还没有找到一个真实的用例,可以通过 docker 主机的内部 IP 地址直接连接到容器,但没有更好的选择。 Instead, if there's post-startup configuration in your container that needs to run, this is often done with an entrypoint script.相反,如果您的容器中有需要运行的启动后配置,则通常使用入口点脚本来完成。

There is also a red flag that you are bypassing docker's networking model.还有一个危险信号表明您正在绕过 docker 的网络模型。 With docker networking, there are two options.使用 docker 网络,有两种选择。 First, when communicating between containers, this is done with a user created network and using docker's built-in DNS to connect to the container by name or network alias rather than by an IP address that would change when the container is recreated.首先,在容器之间进行通信时,这是通过用户创建的网络完成的,并使用 docker 的内置 DNS 通过名称或网络别名而不是通过重新创建容器时会更改的 IP 地址连接到容器。 And for communicating from outside of docker to the container, this is done by publishing a port from the docker host to the container, and then connecting to the host on that port rather than to the container directly.对于从 docker 外部到容器的通信,这是通过从 docker 主机向容器发布一个端口,然后在该端口上连接到主机而不是直接连接到容器来完成的。 If you stick with these two options, you should be able to access your application without ever knowing its internal IP address.如果您坚持使用这两个选项,您应该能够在不知道其内部 IP 地址的情况下访问您的应用程序。

Along with the accepted answer if you need a specific handy alias to get a specific container ip use this alias如果您需要特定的方便别名来获取特定的容器 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'

and then you can get your container ip with然后你可以得到你的容器IP

dockerip <containername>  

You can also use containerid instead of containername您也可以使用 containerid 而不是 containername

BTW accepted great answer doenst produce a clean output so I edited it and using like this ;顺便说一句,接受了很好的答案并没有产生干净的输出,所以我对其进行了编辑并像这样使用;

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'

If you want to quickly see all Docker IP addresses, or without typing the instance name, you can hack the docker ps<\/code> command adding this to your ~\/.bashrc<\/code> file:如果你想快速查看所有 Docker IP 地址,或者不输入实例名称,可以使用docker ps<\/code>命令将其添加到~\/.bashrc<\/code>文件中:

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;
}
docker inspect --format "{{ .NetworkSettings.Networks.mynetwork.IPAddress }}" <containername or containerID here>

以上适用于已设置网络的 Windows 容器

docker create network mynetwork 

docker inspect MY_CONTAINER | jq -r '.[].NetworkSettings.Networks[].IPAddress'<\/code>

plus

  • elegant syntax优雅的语法<\/li>
  • flexible (once you're down with jq you can use it everywhere there's json, very useful)灵活(一旦你使用 jq,你可以在任何有 json 的地方使用它,非常有用)<\/li>
  • powerful强大的<\/li><\/ul>

    minus

    • needs jq installed (eg apt-get install jq)需要安装 jq(例如 apt-get install jq)<\/li><\/ul>"

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

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

this worked for me, I am running on docker-toolbox 18.09.3, at windows 10 home edition:这对我有用,我在 Windows 10 家庭版的 docker-toolbox 18.09.3 上运行:

type command 'docker-machine ls'输入命令'docker-machine ls'

λ docker-machine ls NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS default * virtualbox Running tcp:\/\/192.168.98.100:2376 v18.09.6 λ docker-machine ls NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS default * virtualbox Running tcp:\/\/192.168.98.100:2376 v18.09.6

it would show the actual IP under the URL column.它会在 URL 列下显示实际 IP。 Eg '192.168.98.100'例如'192.168.98.100'

"

Using Python<\/code> New API<\/code> :使用Python<\/code>新API<\/code> :

import docker

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

There are various ways to get the IP of the container from the host有多种方法可以从主机获取容器的 IP

 docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' containerID<\/code><\/pre>

If in case you can't remember the above command you can always do the following<\/strong>如果您不记得上面的命令,您可以随时执行以下操作<\/strong>

docker inspect containerID<\/code>

It will Return low-level information on Docker objects after the information is returned look for "Networks"<\/code> and inside it you will find "IPAddress"<\/code> of container返回信息后,它将返回有关 Docker 对象的低级信息查找"Networks"<\/code> ,在其中您将找到容器的"IPAddress"<\/code>

"

Extract IP Using Arbitrary String:使用任意字符串提取 IP:

Many- nearly all - the solutions I've read in this question require the intermediate step of the user first identifying the <container name> or <container ID> first and then supplying this to their solution to reveal the IP.几乎所有我在这个问题中阅读的解决方案都需要用户首先识别<container name><container ID>的中间步骤,然后将其提供给他们的解决方案以显示 IP。

IPs can change when containers are recreated, and if this happens, any script referencing it will now be broken....重新创建容器时 IP 可能会更改,如果发生这种情况,任何引用它的脚本现在都将被破坏......

So I needed a way of extracting the IP of a container WITHOUT MANUAL INTERVENTION that ensured a script ALWAYS had the correct IP even if it changed every time container was recreated.因此,我需要一种无需手动干预即可提取容器 IP 的方法,以确保脚本始终具有正确的 IP,即使每次重新创建容器时它都会更改。

Solution:解决方案:

#!/bin/bash

# Only need to set "CONTAINERNAME" variable with an arbitrary
# string found in either the Container ID or Image Name and
# it prints container IP. Ensure the string is unique to desired host

CONTAINERNAME='mariadb-blog'
CONTAINERID="$(docker ps | grep -i $CONTAINERNAME | awk '{print $1}')"
CONTAINERIP="$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $CONTAINERID)"

echo "$CONTAINERIP"

Conclusion:结论:

I've tested this script with my own Linux Docker-Compose hosts and it works reliably as of 20220722. Indeed, it's easy to copy-n-paste the script to validate my results are reproducible.我已经用我自己的 Linux Docker-Compose 主机测试了这个脚本,它从 20220722 开始可靠地工作。事实上,很容易复制粘贴脚本来验证我的结果是可重现的。

PLEASE NOTE : There is a potential reliability achilles heal: if you don't cut your own docker images and rely on a third party's, they could change their naming convention of the image and break the grep in the script.请注意:存在潜在的可靠性致命弱点:如果您不剪切自己的 docker 镜像并依赖第三方的镜像,他们可能会更改镜像的命名约定并破坏脚本中的grep Therefore I'd suggest setting the arbitrary string to the Container Name because YOU can control this, ensuring the grep for the string always succeeds and prints the IP to supply to your script.因此,我建议将任意字符串设置为容器名称,因为您可以控制它,确保字符串的 grep 始终成功并打印 IP 以提供给您的脚本。

Best way that no one mention is to assign a hostname to the container.没有人提到的最好方法是为容器分配一个主机名。

docker run -d --hostname localcontainerhostname imageName

This will give you the ip address, but you probably want to use the hostname anyway这将为您提供 ip 地址,但您可能仍想使用主机名

nslookup localcontainerhostname

If you're on Windows, you may not get any information from docker inspect , in which case your best bet is to actually use ipconfig /all and look for the Ethe.net adapter vEthe.net (WSL): section where you can see an IPv4 address.如果你在 Windows,你可能无法从docker inspect获得任何信息,在这种情况下你最好的选择是实际使用ipconfig /all并寻找Ethe.net 适配器 vEthe.net (WSL):你可以看到的部分一个IPv4 地址。 . . . . : xxx.xxx.xxx.xxx (preferred) - this will be the IP you can use in the url on your local browser. :xxx.xxx.xxx.xxx(首选) - 这将是您可以在本地浏览器上的 url 中使用的 IP。

docker inspect <container id> | grep -i "ipaddress"<\/code>

"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Windows 主机获取 Docker 容器的 IP 地址 - How to get a Docker container's IP address from the Windows host 如何从主机访问 Docker 容器的内部 IP 地址? - How to access Docker container's internal IP address from host? 如何从docker容器中获取mac主机IP地址? - How to get mac host IP address from a docker container? 如何从 Windows 主机获取位于桥接网络内的 Docker 容器的 IP 地址? - How to get a Docker container's IP address, located within a bridge network, from a windows host? 从Docker容器中获取主机IP地址 - Get host IP Address from within docker container 如何在docker容器中获取本地主机IP地址? - How to get local host IP address in docker container? 将LAN IP地址分配给Docker容器,与主机的IP地址不同 - Assign LAN IP address to Docker container different from host's IP address 如何在 Docker 桌面 Windows 10 中使用 IP ADDRESS 从主机访问容器(尤其是使用 Z05E406053C418A2DA1) - How to access container from host using IP ADDRESS in Docker Desktop Windows 10 (esspecially with use docker compose)? 从主机访问Docker MySQL服务器,而不需要容器的IP地址 - Accessing a Docker MySQL server from the host machine, without needing the container's IP address 如何获取正在运行的docker容器的IP地址 - How to get IP address of running docker container
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM