Docker 101 : Different ways of exposing / publishing containers ports
Exposing a port through the dockerfile:
We could use the dockerfile to expose port 80 of the container running the below image:
The published port on docker starts a proxy process on the node hosting the container, the proxy service handles the IP forwarding and the NAT (Network Address Translation) and the Masquerading so the traffic could be forwarded to the right container.
This tells docker to map a random port on the host to the port that the container image exposes.
In the case of our container, the image exposes port 80.
Running the container:
We firs run the container using the below command:
-P: exposes the port defined in the dockerfile.
To know which port the container publishes, we use the below command:
Exposing ports om the command line:
The below command runs our image and exposes the port "UDP 8080":
-P : publishes all the exposed ports.
Deciding which port container to expose:
Below are the different arguments we could use with the "-p" option:
In case our host has more than one interface.
Or we could only use only the container's port: