Murali Allada
Murali Allada

Reputation: 22938

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?

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

Upvotes: 2241

Views: 2698119

Answers (30)

WouterD
WouterD

Reputation: 37374

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.

Upvotes: 3688

Peter Kionga-Kamau
Peter Kionga-Kamau

Reputation: 7108

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.

Upvotes: 0

Mariusz
Mariusz

Reputation: 386

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

Upvotes: 0

F1Linux
F1Linux

Reputation: 4383

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.

Upvotes: 7

Krunal
Krunal

Reputation: 7748

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"

Upvotes: 654

lava
lava

Reputation: 7431

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

Upvotes: 8

ctrlbrk
ctrlbrk

Reputation: 1194

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

Upvotes: 37

MKZ
MKZ

Reputation: 186

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

Upvotes: 4

nPcomp
nPcomp

Reputation: 9973

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"

Upvotes: 272

Joel Handwell
Joel Handwell

Reputation: 827

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"

Upvotes: 10

Gene H.
Gene H.

Reputation: 121

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

Upvotes: 10

sedi
sedi

Reputation: 103

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

Upvotes: 9

guneysus
guneysus

Reputation: 6502

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.

Upvotes: 10

ivanleoncz
ivanleoncz

Reputation: 10055

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

Upvotes: 18

Benyamin Jafari
Benyamin Jafari

Reputation: 34176

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'

Upvotes: 23

Rushal Verma
Rushal Verma

Reputation: 416

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.

Upvotes: 23

Jake W
Jake W

Reputation: 2858

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

Upvotes: 51

zhouji
zhouji

Reputation: 5336

Show all container's IP addresses:

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

Upvotes: 51

creack
creack

Reputation: 121742

You can use docker inspect <container id>.

For example:

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

Upvotes: 579

Hadi Mir
Hadi Mir

Reputation: 5133

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

Upvotes: 0

chenchuk
chenchuk

Reputation: 5742

Just another classic solution:

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

Upvotes: 2

LinPy
LinPy

Reputation: 18608

Using Python New API:

import docker

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

Upvotes: 0

Lemix
Lemix

Reputation: 2950

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

Upvotes: 15

gWay
gWay

Reputation: 1245

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'

Upvotes: 0

rustysys-dev
rustysys-dev

Reputation: 863

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.

Upvotes: 4

JakubK
JakubK

Reputation: 163

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

Upvotes: 2

Raj Asapu
Raj Asapu

Reputation: 436

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

Upvotes: 8

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20118

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

Upvotes: 8

Drakes
Drakes

Reputation: 23670

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

Upvotes: 8

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'

Upvotes: 2

Related Questions