How o get the IP address of docker container using docker SDK for python?
Question:
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?
Answers:
Here is an example:
import docker
client = docker.DockerClient()
container = client.containers.get("magical_meitner")
ip_add = container.attrs['NetworkSettings']['IPAddress']
print(ip_add)
If the IP doesn’t return from container.attrs['NetworkSettings']['IPAddress']
as suggested here, try the following:
network_name = "my_net"
container.attrs["NetworkSettings"]["Networks"][network_name]["IPAddress"]
For me, this was the case when the containers were created with docker-compose, with an external network.
container.attrs.get("NetworkSettings", {}).get("Networks", {}).get(network.name, {}).get("IPAddress")
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?
Here is an example:
import docker
client = docker.DockerClient()
container = client.containers.get("magical_meitner")
ip_add = container.attrs['NetworkSettings']['IPAddress']
print(ip_add)
If the IP doesn’t return from container.attrs['NetworkSettings']['IPAddress']
as suggested here, try the following:
network_name = "my_net"
container.attrs["NetworkSettings"]["Networks"][network_name]["IPAddress"]
For me, this was the case when the containers were created with docker-compose, with an external network.
container.attrs.get("NetworkSettings", {}).get("Networks", {}).get(network.name, {}).get("IPAddress")