Search code examples
pythondockersdkdocker-network

How to get the IP address of Docker container using Docker SDK for Python?


I am launching a container with network_mode = bridge, when I inspect the network container in the terminal I get the container IP address.

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

However, I can't get this IP address from the container object. Is there any solution without searching the container in the network object?


Solution

  • Here is an example:

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

    You may need to call container.reload() first to update the attributes (reference).