Docker-py: How do I find container ports?

Created on 13 Sep 2017  路  2Comments  路  Source: docker/docker-py

I'm trying to create an index page for a test server that is autogenerated and just prints the name of the docker container and the port it is running on as a hyperlink. However I don't seem to be able to find a way to retrieve the port the containers are running on from your documentation. Could you give me an example of how to do this please?

Most helpful comment

You 'll have to use the low-level API for that:

import docker
client = docker.APIClient(base_url='unix://var/run/docker.sock')
port_data = client.inspect_container(<container_id>)['NetworkSettings']['Ports']

All 2 comments

You 'll have to use the low-level API for that:

import docker
client = docker.APIClient(base_url='unix://var/run/docker.sock')
port_data = client.inspect_container(<container_id>)['NetworkSettings']['Ports']

With #1882 (so presumably available on the versions that will follow 3.7.2) there is now a second way of doing this:

import docker
client = docker.from_env()
container = client.containers.run("alpine", "sleep 100", detach=True)
container.reload()  # required to get auto-assigned ports, not needed if it was an already running container
print(container.ports)
Was this page helpful?
0 / 5 - 0 ratings