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 to 1234
(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 the NetworkSettings
...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
.
The left-hand side of the port number mapping is the Docker host port to map to and the right-hand side is the Docker container port number. When you open the browser and navigate to the Docker host on port 8080, you will see Jenkins up and running.
The EXPOSE instruction exposes a particular port with a specified protocol inside a Docker Container. In the simplest term, the EXPOSE instruction tells Docker to get all its information required during the runtime from a specified Port. These ports can be either TCP or UDP, but it's TCP by default.
You cannot do this via Docker, but you can access the container's un-exposed port from the host machine.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With