7

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?

4
  • Did you check the docker networking documentation? Commented Oct 11, 2019 at 9:45
  • Yes, but didn't help, I need to use docker SDK for python because the interactions with the docker daemon are from the flask server. Commented Oct 11, 2019 at 10:00
  • Looking up this IP address is almost never necessary (it simply doesn't work in several common situations); why do you want it? Commented Oct 11, 2019 at 10:27
  • It is an academic project but basically, I want to implement a policy rule in the openvswitch where I restrict access to that container based on the IP address. Commented Oct 11, 2019 at 13:28

3 Answers 3

19

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1
container.attrs.get("NetworkSettings", {}).get("Networks", {}).get(network.name, {}).get("IPAddress")

1 Comment

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.