When I launch a container using the docker SDK for Python, I can specify the host port as None
so that the SDK will pick a random available port for me:
import docker
client = docker.from_env()
container = client.containers.run(
"bfirsh/reticulate-splines",
ports={6379 : None} # SDK chooses a host port
detach=True)
The problem is that I want to know after the run command which host port did the SDK choose. How do I do that?
CodePudding user response:
You need to reload the container then use container.ports
import docker
client = docker.from_env()
container = client.containers.run(
"bfirsh/reticulate-splines", ports={6379: None}, detach=True
)
container.reload() # need to reload
print(container.ports)
Output
{'6379/tcp': [{'HostIp': '0.0.0.0', 'HostPort': '53828'}]}
This is only in version greater than 4.0.2 (which is at least 4 years old now)
Commit that added this attribute
CodePudding user response:
Unfortunately a Container
object does not have a ports
attribute (prior to 3.7.2 as @python_user notes). By printing the attrs
dictionary I was able to find out that the host port is contained inside the NetworkSettings
attribute. In my case retrieving the host port looks like this:
attrs['NetworkSettings']['Ports']['6379/tcp'][0]['HostPort']
# container port specified at launch ^^^
A more general solution would be to avoid the container port (6379) and search for the 'HostPort'
key instead.