6

I would like to get the ipaddress of the containers and I trying to figure out how using python docker APIs.

Something like this I would like to do it in python APIs

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

I tried this and coming back null for ip address

import docker
dockerClient = docker.from_env()

client = docker.APIClient(base_url='unix://var/run/docker.sock')
for container in dockerClient.containers.list():
    print container.id
    print "-------------"
    print client.inspect_container(container.id)['NetworkSettings']['IPAddress']
user2511126
  • 620
  • 1
  • 14
  • 31
  • You almost never want the container-internal IP addresses for anything: they change routinely and are unreachable in many common circumstances. Why are you trying to look this up? – David Maze Feb 26 '19 at 11:28

2 Answers2

6
import docker 
client = docker.APIClient(base_url='unix://var/run/docker.sock') 
my_c = client.inspect_container('id_container')
print(my_c['NetworkSettings']['Networks']['bridge']['IPAddress'])
JavMM
  • 71
  • 1
3

This can be done using docker-py, you can check the following

Try the following:

print client.inspect_container(container.id)['NetworkSettings']['Networks']['bridge']['IPAddress']

Note that you may want to loop on the Networks (in case you have multiple network and you want all IPs) or change bridge to the appropriate network name as bridge will be the default network name.

Mostafa Hussein
  • 11,063
  • 3
  • 36
  • 61
  • 1
    In version 3.7.2 it will be something like client.api.inspect_container('elasticsearch')['NetworkSettings']['Networks']['dockerfiles_default']['IPAddress'] – Vasili Pascal May 16 '19 at 08:13
  • @VasiliPascal the `client.api.inspect_container` is not document yet, am i right ? I just don't want to add an updated answer unless its confirmed – Mostafa Hussein May 16 '19 at 09:58
  • Probably docs were not updated, I found it using ipython, (python3) – Vasili Pascal May 16 '19 at 13:25