2121

Is there a command I can run to get the container's IP address right from the host after a new container is created?

Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.

Naman
  • 27,789
  • 26
  • 218
  • 353
Murali Allada
  • 21,718
  • 4
  • 19
  • 21
  • 54
    I just wanted to make sure other noobs don't make my mistake and try to get the IP from the image instead of the container. Ensure you get the CID or container id and query that; CID via 'docker ps' that is. – Paul Gregoire Jan 19 '15 at 18:06

56 Answers56

3494

This solution only works if the container is connected with a single network. The --format option of inspect comes to the rescue.

Modern Docker client syntax is:

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

Old Docker client syntax is:

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

These commands will return the Docker container's IP address.

As mentioned in the comments: if you are on Windows, use double quotes " instead of single quotes ' around the curly braces.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
WouterD
  • 35,410
  • 2
  • 13
  • 6
  • 52
    This is a much, MUCH better solution. Only ask for what you need, if possible! – MikeyB Jan 07 '14 at 02:19
  • 15
    Hmm. Getting a `` response on a Mac using Fig/Boot2Docker – cevaris Nov 24 '14 at 14:57
  • 1
    @cevaris Check you are using the right CID or name, the `inspect` command will match images first which will obviously have no IP! – Matthew Wilcoxson Mar 30 '15 at 18:05
  • 84
    !WARNING! This doesn't work anymore. The new format is specific to the container and follows the form ```{{ .NetworkSettings.Networks.$network.IPAddress }}```. The default appears to be bridge, but under docker-compose this will be a specific name that depends on the name of your app (I think from the --project-name flag, though that's also going to depend on what type of networking config you have set up). I wrote a full answer in an answer here http://stackoverflow.com/questions/17157721/getting-a-docker-containers-ip-address-from-the-host/31559812#31559812 – Dunk Feb 10 '16 at 15:46
  • I also use that, but it doesn't work if the container is in a custom network. I'm trying to find a command that works in all cases – Federico Razzoli Sep 14 '16 at 12:46
  • Should this even be an option? I mean, if you want to access a Docker external from outside the container, it’s 127.0.0.1 or eth0 IP. If it’s internal, Docker already has a mechanism for linking the containers so they know how to communicate with each other? – Hayden Oct 08 '17 at 04:19
  • @Hayden On Linux, it’s easier. On Windows, nothing is quite so well designed as 127.0.0.1 is broken by default. See https://stackoverflow.com/questions/40746453/how-to-connect-to-docker-host-from-container-on-windows-10-docker-for-windows# – Contango Nov 02 '17 at 18:02
  • On Windows it failed at first. It succeeds when running with PowerShell. BIG thumbs up! Thanks – Asaf Savich Mar 20 '18 at 14:47
  • Template parsing error: template: :1: unexpected unclosed action in range – bdaniel7 Oct 22 '18 at 10:22
  • Checkout the gist https://gist.github.com/Lewiscowles1986/2c80f1e510152b461eae5c501a00a195 – MrMesees Nov 24 '18 at 18:32
  • I am using fedora 24 and command only works with container id – Sarasa Gunawardhana Jan 24 '19 at 08:52
  • 1
    Note, IP address will be empty if container runs in host networking mode. – Hem Feb 28 '19 at 19:42
  • https://gist.github.com/hikermillerman/0a59c538011e8532164016193b088f08 – Vadiraj Purohit Mar 28 '19 at 23:52
  • 11
    Maybe I am a sleepy sheep, but the warning about double quotes was not bold and blinky enough to catch my attention. Maybe provide two examples clearly labelled Linux and Windows. I literally just typed the example, checked the docs [which also uses single quotes](https://docs.docker.com/engine/reference/commandline/inspect/) and then Googled the error. I'm sure I'm not alone. – Wyck Apr 15 '19 at 18:42
  • 2
    In case of docker-compose project, required format is: {{ .NetworkSettings.Networks..IPAddress }} ; by default is _default – Filip Malczak May 15 '19 at 15:58
  • 5
    Solution for peoples getting formatting error: `docker inspect and scroll down you will find the container ip-address` – Ivandro Jao Jun 28 '19 at 17:13
  • If your network name starts with a number or includes a hyphen: `docker inspect --format '{{(index .NetworkSettings.Networks "1-network_name").IPAddress}}' container_name` – PrplHaz4 Nov 27 '19 at 03:47
  • This will get the list of hostnames and IPs of all containers: `for N in $(docker-compose ps -q) ; do echo "$(docker inspect -f '{{.Config.Hostname}}' ${N}) $(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ${N})"; done` – Ray May 04 '20 at 09:56
  • 3
    This does not work well with multiple networks. I want to index the IP of one container – MKZ Jul 03 '20 at 18:00
  • I'm using docker compose on ubuntu WSL 2.0 from a Windows 10. This works for me. But would be nice to only get the internal IP... which appears to be the first one in my case for a handful of containers. The sed removes lines not ending in a number and it lists the names of each container. docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' $(docker ps -aq) | sed -e '/ [^0-9]$/d' – Liam Mitchell Jan 29 '21 at 06:25
  • Upvoted both question and answer, and then built my own solution based on the answer. Docker 19+ allows people to build custom plugins. Here is mine to get the IP addresses of all running containers. https://github.com/Vinayakj009/Docker-GetIP – Nitro Feb 08 '21 at 07:23
  • At least from a Windows cmd prompt the new command seems to also work with single quotes. – Jonathan Sep 27 '21 at 14:01
  • Listing all containers and IPs: Ray's solution only listed some of my containers, also I prefer container names to hashes. `docker ps --format "{{.Names}}" | while read cid b; do echo -n "$cid\t\t"; docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $cid; done` Built from ko-dos's below. – Noumenon Jan 30 '22 at 17:50
  • You would think they would make this easier given how common it is... – Francisco Aguilera Mar 28 '22 at 21:03
592

First get the container ID:

docker ps

(First column is for container ID)

Use the container ID to run:

docker inspect <container ID>

At the bottom, under NetworkSettings, you can find IPAddress

Or just do for UNIX based:

docker inspect <container id> | grep "IPAddress"

And for Windows CMD:

docker inspect <container id> | findstr "IPAddress"
Rich
  • 3,928
  • 4
  • 37
  • 66
Krunal
  • 7,048
  • 1
  • 18
  • 19
  • 11
    Too bad, on one of my instances (started with `docker run -it MYCONTAINER /bin/bash`), the output of `inspect` has no section `NetworkSettings`! – Eric Oct 12 '17 at 10:16
  • 6
    This doesn´t work on Windows 10. You need too find out the ip address of DockerNAT with ipconfig. – ntiedt Nov 07 '17 at 15:30
  • 2
    @Eric You can also inspect network bridge for that: `docker network inspect bridge | grep Gateway | grep -o -E '[0-9.]+'` – Tomasz Kapłoński Feb 13 '18 at 07:12
  • `docker inspect | jq -r .[0].NetworkSettings.IPAddress` – forzagreen May 03 '18 at 09:52
  • can also use container name instead of container id. – Banee Ishaque K Aug 20 '18 at 14:09
  • Also, based on rajdeepbs29 solution, you can do this executing: docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq) – Jose Ignacio Centeno Aug 23 '18 at 10:23
  • 7
    I greatly prefer the `... | grep IP` solution to all the formatting details required to get IP. +1 – d8aninja Mar 06 '19 at 17:49
  • 4
    @Eric - you've confused *container* with *image*. The command is actually `docker run -it MYIMAGE` (that isn't a *container* name); if you do `docker inspect MYIMAGE` you will get static information about the *image*. You need to find the name of the *running container* (or use its id as others suggest). On my system, the first such container created from that image defaults to name `MYIMAGE_1`, so `docker inspect MYIMAGE_1` has NetworkSettings. – ToolmakerSteve Mar 29 '19 at 19:27
  • @ToolmakerSteve yup I inspected the image instead of the container indeed. And as you wrote the former returns details about the image whereas the later has a `NetworkSettings` section. – Eric Mar 30 '19 at 20:25
  • @ntiedt !! This should be an answer, it's not visible enough as a comment... – Peter Kionga-Kamau Nov 12 '22 at 18:17
576

You can use docker inspect <container id>.

For example:

CID=$(docker run -d -p 4321 base nc -lk 4321);
docker inspect $CID
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
creack
  • 116,210
  • 12
  • 97
  • 73
  • 69
    In order to extract the ip, you can do something like `docker inspect $CID | grep IPAddress | cut -d '"' -f 4`, it works fine :) – creack Jun 17 '13 at 23:39
  • 12
    Bringing it all together, this shell alias should list all container ids and their ips: `alias dockerip='docker ps | tail -n +2 | while read cid b; do echo -n "$cid\t"; docker inspect $cid | grep IPAddress | cut -d \" -f 4; done'` – ko-dos Dec 12 '13 at 11:22
  • 66
    As mentionned by @user3119830, there is a new option to inspect. Now, you can get the Ip easier with `docker inspect -format '{{ .NetworkSettings.IPAddress }}' ${CID}` – creack Jan 07 '14 at 02:48
  • 17
    Just a note. The single dash options are being deprecated so that -format will become --format. – jamtur01 Mar 22 '14 at 01:42
  • 8
    `docker inspect -format '{{ .NetworkSettings.IPAddress }}' ${CID}` is the new syntax. `-format` is deprecated, it becomes `--format`. – Devy Aug 10 '15 at 22:09
  • That is working for me now (mid 2017 is): `docker inspect --format '{{ range .NetworkSettings.Networks }}{{ .IPAddress }}{{ end }}' ${CID}` – ThiagoAlves Aug 02 '17 at 18:13
  • `docker inspect 5dfb2e7bfe83 | findstr /i address` does not return address with the same value as shown in kitematic. The address shown in kitematic works. The address shown through inspect command does not. – tatmanblue Aug 14 '17 at 19:13
270
docker inspect CONTAINER_ID | grep "IPAddress"

You can add -i to grep for ignoring the case then even the following will work:

docker inspect CONTAINER_ID | grep -i "IPaDDreSS"
nPcomp
  • 8,637
  • 2
  • 54
  • 49
212

To get all container names and their IP addresses in just one single command.

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

If you are using docker-compose the command will be this:

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hemerson Varela
  • 24,034
  • 16
  • 68
  • 69
  • 9
    I really like this but it doesn't work for Docker Compose as well, something to do with having their own network. Instead change `{{.NetworkSettings.IPAddress }}` to `{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}` – clockworkgeek Mar 13 '16 at 16:57
  • Here's the variation I use: `docker inspect --format '{{ .NetworkSettings.IPAddress }}' $(docker ps -aq | xargs) | sed -e '/^$/d'`. The `sed(1)` removes empty lines for containers present, but not having an IP-address. – NYCeyes Feb 05 '20 at 16:01
  • A little bit lame addition, but for anyone who needs to execute this command with `sudo`, here is this one liner: `docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}' $(sudo docker ps -aq)` – Bart Feb 15 '23 at 01:32
  • Does not work correctly when a container is connected with multiple docker networks. – Chris Stryczynski Jun 14 '23 at 13:13
105

Add this shell script in your ~/.bashrc or relevant file:

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

Then, to get an IP address of a container, simply do this:

docker-ip YOUR_CONTAINER_ID

For the new version of the Docker, please use the following:

docker-ip() {
        docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$@"
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tuong Le
  • 18,533
  • 11
  • 50
  • 44
  • 6
    `Template parsing error: template: :1:19: executing "" at <.NetworkSettings.IPA...>: map has no entry for key "NetworkSettings"` – saiyancoder Dec 11 '16 at 17:27
  • this works for me, but need to```source ~/.bash_profile``` – penny chan Jun 30 '17 at 02:28
  • 3
    You will get this error if you are not inspecting a running container, but just an image... an image doesn't have an IPAddress... terrible error message, yes – dagelf Mar 31 '19 at 09:43
49

In Docker 1.3+, you can also check it using:

Enter the running 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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Jake W
  • 2,788
  • 34
  • 39
47

Show all container's IP addresses:

docker inspect --format='{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
zhouji
  • 5,056
  • 1
  • 26
  • 26
37

As of Docker version 1.10.3, build 20f81dd

Unless you told Docker otherwise, Docker always launches your containers in the bridge network. 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.

[
    {
        "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"
        }
    }
]
Athena
  • 371
  • 3
  • 2
37

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:

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:

# 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
ctrlbrk
  • 1,174
  • 2
  • 17
  • 27
34

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:

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

"172.17.0.2"

gogasca
  • 9,283
  • 6
  • 80
  • 125
28

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. They are now in my .bashrc file.

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.

docker-ips
docker-ip YOUR_CONTAINER_ID
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
silgon
  • 6,890
  • 7
  • 46
  • 67
23

Docker is written in Go and it uses Go syntax for query purposes too.

To inspect the IP address of a particular container, you need to run the command (-f for "format"):

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

For the container ID or name, you can run the command

docker container ls

which will list every running container.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Rushal Verma
  • 416
  • 3
  • 13
22

I wrote the following Bash script to get a table of IP addresses from all containers running under docker-compose.

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dunk
  • 1,336
  • 12
  • 16
  • 1
    Tuong Le answer from here https://stackoverflow.com/questions/17157721/how-to-get-a-docker-containers-ip-address-from-the-host/31559812#31559812 avoids having to specify the network in dip(): docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$@" – JoanComasFdz Jan 21 '19 at 14:42
22

Here's a quick working answer:

Get your container name or ID:

docker container ls

Then get the IP:

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

Get the port:

docker inspect <container_ID Or container_name> |grep 'Port'
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
19

Reference containers by name:

docker run ... --name pg-master

Then grab the IP address address by name:

MASTER_HOST=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' pg-master)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sameer C
  • 2,777
  • 1
  • 18
  • 12
18

Here's is a solution that I developed today in Python, using the docker inspect container JSON output as the data source.

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.

#!/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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
  • Please, change to python2.7 in a script, python3 is now in common use or write two versions – 42n4 Apr 18 '17 at 21:36
  • I'll update my Gist and as soon as I have it, I'll post here. Indeed, this wrapper was designed for Python 2.7. Thanks for the feedback! – ivanleoncz Apr 18 '17 at 21:38
14

I use this simple way

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

e.g

ubuntu@myhost:~$ docker exec -it 3d618ac670fe hostname -i
10.0.1.5
Lemix
  • 2,415
  • 1
  • 15
  • 16
10

To extend ko-dos' answer, here's an alias to list all container names and their IP addresses:

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'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marco Roy
  • 4,004
  • 7
  • 34
  • 50
  • 1
    That can be simplified quite a bit - use `docker ps -q` to avoid the `tail`, and `--format` to avoid the grep. Also you can pass multiple container IDs to `docker inspect` rather than loop in shell. – Bryan May 06 '15 at 10:45
  • 1
    `docker ps -q` only displays the containers' numeric IDs, but I think using their name is better. `tail` is only to get rid of the first line (table header) & is still needed. I could use `--format`, though: `docker ps | tail -n +2 | while read -a a; do name=${a[$((${#a[@]}-1))]}; echo -ne "$name\t"; docker inspect --format="{{.NetworkSettings.IPAddress}}" $name | cut -d \" -f 4; done`. But that doesn't seem like a big improvement... the `grep` was more readable IMO. – Marco Roy May 08 '15 at 01:01
  • 1
    Slightly altered version which lists IPs first, in one line together with the container name: docker ps | tail -n +2 | while read -a a; do name=${a[$((${#a[@]}-1))]}; docker inspect $name | grep "IPAddress.*[0-9]\+" | cut -d \" -f 4 | tr "\n" " "; echo -e "\t${name}"; done – Gilead Oct 21 '16 at 09:56
  • Ended up with : `docker inspect $cid | grep IPAddress | cut -d '"' -f 4 | tail -n 1` – antogerva Oct 25 '18 at 20:03
  • 1
    Actually like the style of this better `docker ps | tail -n +2 | while read -a a; do name=${a[$((${#a[@]}-1))]}; echo ${name};docker inspect $name | grep "IPAddress.*[0-9]\+"; done` – Dennis G Jan 11 '22 at 08:43
10

Combining previous answers with finding the container ID based on the Docker image name:

docker inspect --format '{{ .NetworkSettings.IPAddress }}' `docker ps | grep $IMAGE_NAME | sed 's/\|/ /' | awk '{print $1}'`
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Gene H.
  • 121
  • 1
  • 3
10

NOTE!!! for Docker Compose Usage:

Since Docker Compose creates an isolated network for each cluster, the methods below do not work with docker-compose.


The most elegant and easy way is defining a shell function, currently the most-voted answer @WouterD's:

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

Docker can write container IDs to a file like Linux programs:

Running with --cidfile=filename, Docker dumps the ID of the container to "filename".

See "Docker runs PID equivalent Section" for more information.

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

Using a PID file:

  1. Running container with --cidfile parameter, the app.cid file content is like:

    a29ac3b9f8aebf66a1ba5989186bd620ea66f1740e9fe6524351e7ace139b909
    
  2. You can use file content to inspect Docker containers:

    blog-v4 git:(develop) ✗ docker inspect `cat app.cid`
    
  3. You can extract the container IP using an inline Python script:

    $ 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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
guneysus
  • 6,203
  • 2
  • 45
  • 47
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}'
Aravind Murthy
  • 501
  • 6
  • 8
10

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.

docker inspect $CID | jid

Type Tab .Net Tab and you'll see something like:

[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:

[Filter]> .[0].NetworkSettings.IPAddress
"172.17.0.2"
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Joel Handwell
  • 742
  • 1
  • 10
  • 18
9

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:

docker inspect <CONTAINER> |python -c 'import json,sys;obj=json.load(sys.stdin);print obj[0]["NetworkSettings"]["IPAddress"]'
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
sedi
  • 103
  • 1
  • 6
8

If you installed Docker using Docker Toolbox, you can use the Kitematic application to get the container IP address:

  1. Select the container
  2. Click on Settings
  3. Click in Ports tab.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fernando Montoya
  • 2,625
  • 1
  • 18
  • 21
  • For me, the IP address was on the "Hostname/ports" tab, but this was nevertheless a very helpful answer! Note that `docker inspect` does not work when you run docker toolbox. It will report an IP address, but it is not the correct address that your services will use. – Göran Roseen Sep 10 '18 at 12:55
8

To get the IP address and host port of a container:

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

Output:

    "HostPort": "4200"
                    "HostPort": "4200"
        "SecondaryIPAddresses": null,
        "IPAddress": "172.17.0.2",
                "IPAddress": "172.17.0.2",
ssmith
  • 8,092
  • 6
  • 52
  • 93
Raj Asapu
  • 436
  • 5
  • 11
8

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:

> 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:

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",
Drakes
  • 23,254
  • 3
  • 51
  • 94
7

For windows 10:

docker inspect --format "{{ .NetworkSettings.IPAddress }}"  containerId
Hai Nguyen
  • 1,675
  • 19
  • 14
7

This will list down all the container IPs on the host:

sudo docker ps -aq | while read line;  do sudo docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $line ; done
sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
rajdeepbs29
  • 1,211
  • 12
  • 9
7

Docker inspect use to print all container ips and its respective names

docker ps -q | xargs -n 1 docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} {{ .Name }}' | sed 's/ \// /'
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
6

Linux Container

. Method 1

 docker exec postgres ifconfig

enter image description here

. Method 2

  docker exec postgres cat /etc/hosts

enter image description here

. Method 3

docker exec postgres ip a

enter image description here

. Method 4

With Powershell

docker inspect postgres | select-string 'ipaddress'

enter image description here

lava
  • 6,020
  • 2
  • 31
  • 28
6

Extract IP Using Arbitrary String:

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.

IPs can change when containers are recreated, and if this happens, any script referencing it will now be broken....

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.

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.

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. 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.

F1Linux
  • 3,580
  • 3
  • 25
  • 24
5

Use:

docker inspect $CID | grep IPAddress | grep -v null| cut -d '"' -f 4 | head -1
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex Liffick
  • 129
  • 2
  • 9
  • This is the actual single line proper command. Here's what I got. `$ docker inspect c4591485328d | grep IPAddress | grep -v null| cut -d '"' -f 4 | head -1` `172.17.0.2` – Jayant Bhawal Aug 19 '16 at 13:08
5
docker inspect <container id> | grep -i ip

For example:

docker inspect 2b0c4b617a8c | grep -i ip
Roman
  • 19,236
  • 15
  • 93
  • 97
4

For Windows containers use

docker exec <container> ipconfig

where <container> is the name or the id of the container.

You can use docker ps to find the id of the container.

kirodge
  • 676
  • 5
  • 23
  • Remember to use “—rm” or else it will slowly eat up hard drive space with undeleted layers. It is good to pair “—rm” with “run” in almost all cases. – Contango Nov 02 '17 at 18:07
  • @Contango: 'docker exec' executes a command in a already running container. It doesn't have a --rm switch. https://docs.docker.com/engine/reference/commandline/exec/ – kirodge Nov 03 '17 at 15:29
  • I am on windows, using Docker Desktop. I typed C:\Users\"myname"> docker exec docker_database_1 ipconfig I get: OCI runtime exec failed: exec failed: container_linux.go:367: starting container process caused: exec: "ipconfig": executable file not found in $PATH: unknown You sure it work? – korvus Apr 29 '21 at 14:00
  • @korvus You are on Windows - but are you running Docker Desktop in Windows Container mode or Linux Container mode? The error you got contains the words "container_linux" - so I suspect that you might be running a linux container. – kirodge May 04 '21 at 18:11
4

If you forgot container ID or don't want to manipulate with shell commands, it's better to use UI like Portainer.

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.

igor
  • 81
  • 10
  • 4
    While this link may answer the question, link only answers are discouraged on Stack Overflow, you can improve this answer by taking vital parts of the link and putting it into your answer, this makes sure your answer is still an answer if the link gets changed or removed :) – WhatsThePoint Dec 04 '17 at 13:30
4

Nobody has proposed the Docker Python API yet. Docker API solution to get IP Address is fairly simple.

*NIX based OS: docker api 3.7 (updated thanks to canadadry from the comments)

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)

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.

rustysys-dev
  • 843
  • 1
  • 11
  • 22
3

Inspect didn't work for me. Maybe as I was using -net host and some namespaces.

Anyway, I found this to work nicely:

docker exec -i -t NAME /sbin/ifconfig docker0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Goblinhack
  • 2,859
  • 1
  • 26
  • 26
3

I had to extract docker container IP Adress by docker container name for further usage in deployment scripts. For this purpose I have written the following bash command:

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\}'

Suppose it could be handy to place it into a bash script, which would expect my_container_name as an argument...

Oleksii Zymovets
  • 690
  • 8
  • 14
3

This script will get the IPv4 address for all running containers without further processing or interpreting results. If you don't want the container name as well, you can just remove the "echo -n $NAME:" line. 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"'
  • updated dockerip : ```alias dockerip="docker ps --format {{.Names}} | xargs -L1 -I{} bash -c \"echo -n \{}:; docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' {}\""``` – Tony Mar 19 '18 at 16:25
3

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. 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. 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 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. 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.


Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.

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. 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. With docker networking, there are two options. 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. 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. If you stick with these two options, you should be able to access your application without ever knowing its internal IP address.

BMitch
  • 231,797
  • 42
  • 475
  • 450
  • In case you want the first ip address in bash, you can use this code: `ips=($(docker container inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' test-apache)) ; host=${ips[0]}` – Christian Hujer Sep 05 '18 at 13:53
3

I had troubles with my multi-network environment so this is a more dynamic version

Get all hostnames, networks and IPs residing in one compose file

 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

Outputs

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

To get all running containers replace the first command

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

with

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

Get IP of 1 specific container (with multiple networks), given 1 specific network

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

Outputs

192.168.1.4

Get 'Hostname IP' of all containers (with multiple networks), given 1 specific network

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

Outputs

containerA 192.168.1.4
containerB 192.168.1.5

Get IP of all containers (with multiple networks), given 1 specific network

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

Outputs

192.168.1.4
192.168.1.5
MKZ
  • 166
  • 1
  • 12
2

Try in Windows PowerShell:

     docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" <container id>
Md. Ilyas Hasan Mamun
  • 1,848
  • 2
  • 24
  • 15
2

docker inspect MY_CONTAINER | jq -r '.[].NetworkSettings.Networks[].IPAddress'

plus

  • elegant syntax
  • flexible (once you're down with jq you can use it everywhere there's json, very useful)
  • powerful

minus

  • needs jq installed (e.g. apt-get install jq)
Nick
  • 376
  • 3
  • 8
2

Along with the accepted answer if you need a specific handy alias to get a specific container ip use this alias

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

dockerip <containername>  

You can also use containerid instead of 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'
Erdinç Çorbacı
  • 1,187
  • 14
  • 17
2

Check this script: https://github.com/jakubthedeveloper/DockerIps

It returns container names with their IP's in the following format:

abc_nginx 172.21.0.4
abc_php 172.21.0.5
abc_phpmyadmin 172.21.0.3
abc_mysql 172.21.0.2
JakubK
  • 153
  • 2
  • 9
2

Just another classic solution:

docker ps -aq | xargs docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}'
chenchuk
  • 5,324
  • 4
  • 34
  • 41
  • For me does not work, but works this: docker ps -aq | xargs docker inspect -f '{{.Name}} - {{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' – Sergey Onishchenko Feb 10 '22 at 04:49
1

If you want to quickly see all Docker IP addresses, or without typing the instance name, you can hack the docker ps command adding this to your ~/.bashrc file:

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;
}

This comes from a proposal by Andrew Johnstone at the Docker GitHub: https://github.com/docker/docker/issues/8786

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nicolas Zozol
  • 6,910
  • 3
  • 50
  • 74
1
docker inspect --format "{{ .NetworkSettings.Networks.mynetwork.IPAddress }}" <containername or containerID here>

The above is for windows containers where a network has been set up with a

docker create network mynetwork 
navarq
  • 1,075
  • 2
  • 15
  • 20
0

this worked for me, I am running on docker-toolbox 18.09.3, at windows 10 home edition:

type command '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

it would show the actual IP under the URL column. E.g. '192.168.98.100'

gWay
  • 1,087
  • 9
  • 7
0

Using Python New API:

import docker

client = docker.DockerClient()
container = client.containers.get("NAME")
ip_add = container.attrs['NetworkSettings']['IPAddress']
print(ip_add)
LinPy
  • 16,987
  • 4
  • 43
  • 57
0

There are various ways to get the IP of the container from the host

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

If in case you can't remember the above command you can always do the following

docker inspect containerID

It will Return low-level information on Docker objects after the information is returned look for "Networks" and inside it you will find "IPAddress" of container

Hadi Mir
  • 4,497
  • 2
  • 29
  • 31
0

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

nslookup localcontainerhostname
Mariusz
  • 346
  • 3
  • 6
0

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 Ethernet adapter vEthernet (WSL): section where you can see an IPv4 address . . . : xxx.xxx.xxx.xxx (preferred) - this will be the IP you can use in the url on your local browser.

Peter Kionga-Kamau
  • 6,504
  • 2
  • 17
  • 13
-1

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

alamin
  • 2,377
  • 1
  • 26
  • 31
-6
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
Will
  • 24,082
  • 14
  • 97
  • 108
Girish
  • 1