How can I grab exposed port from inspecting docker container?
Solution 1
Execute the command: docker inspect --format="{{json .Config.ExposedPorts }}" src_python_1
Result: {"8000/tcp":{}}
Proof (using docker ps
):
e5e917b59e15 src_python:latest "start-server" 22 hours ago Up 22 hours 0.0.0.0:8000->8000/tcp src_python_1
Solution 2
It is not easy as with ip address as one container can have multiple ports, some exposed and some not, but this will get it:
sudo docker inspect name | grep HostPort | sort | uniq | grep -o [0-9]*
If more than one port is exposed it will be displayed on a new line.
Solution 3
There are two good options depending on your taste: docker port my-container 1234 | grep -o [0-9]*$
and docker inspect --format='{{(index (index .NetworkSettings.Ports "1234/tcp") 0).HostPort}}' my-container
Solution 4
Using jq:
docker inspect --format="{{json .}}" my-container | jq '.NetworkSettings.Ports["1234/tcp"][0].HostPort'
Change 1234 with the port you specified in docker run
.
Comments
-
TheJediCowboy almost 2 years
Assuming that I start a docker container with the following command
docker run -d --name my-container -p 1234 my-image
and running
docker ps
shows the port binding for that image is...80/tcp, 443 /tcp. 0.0.0.0:32768->1234/tcp
Is there a way that I can use
docker inspect
to grab the port that is assigned to be mapped to1234
(in this case, 32768)?Similar to parsing and grabbing the IP address using the following command...
IP=$(docker inspect -f "{{ .Networksettings.IPAddress }} my-container)
I want to be able to do something similar to the following
ASSIGNED_PORT=$(docker inspect -f "{{...}} my-container)
I am not sure if there is a way to do this through Docker, but I would imagine there is some command line magic (grep,sed,etc) that would allow me to do something like this.
When I run
docker inspect my-container
and look at theNetworkSettings
...I see the following"NetworkSettings": { ... ... ... "Ports": { "1234/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "32768" } ], "443/tcp": null, "80/tcp": null }, ... ... },
In this case, I would want it to find HostPort without me telling it anything about port 1234 (it should ignore 443 and 80 below it) and return
32768
.