Port mapping while spinning container

My simple dockerfile to test ports
FROM nginx

I exposed port 80 in dockerfile, created image and then spinned up container

docker run -P imagename

docker ps // this command showed me>80/tcp in that container details

On my local host browser I could see nginx server up (http://<dockermachine_ip>:32768/)

What does it mean? this expose in dockerfile has any affect with -P option in run command ??
-P option makes any random port in localhost as available in this way ?

Also now in another scenario I have spinned up container with exposing port 8080(dockerfile below two lines)

FROM nginx

Now surprisingly I noiticed two ports in PORTS section of container info when I ran docker ps.>80/tcp,>8080/tcp

Not sure why the behaviour is different in two scenarios? Some one pls help.Also please let me know what rule here docker machine is following while assigning ips/port bnding…etc… TIA

That’s pretty much right. AFAICT that’s the only effect of EXPOSE, beyond documenting which port your service intends to listen on. It’s much more common to use docker run -p (little “p”) which allows you to pick the host port.

I bet the nginx base image already has an EXPOSE 80 line, and they add, so you get both.

Since Docker will remap ports, and since a container should only run one service, IMHO it’s better to run services on their normal ports: if you’re serving HTTP, do it on port 80, and either use docker run -p to access individual services or a private network, Docker’s internal DNS service, and a reverse proxy for a collection of services.

1 Like

Thanks David for the information provided

As I have said its giving two ports(used -P) which were exposed in dockerfile.>80/tcp,>8080/tcp

In the browser http://<dockermachine_ip>:32770 is working and showing output but http://<dockermachine_ip>:32769 is not up and showing nothing

Any idea why its not up in port 32769 (though 8080 exposed in dockerfile) ??

Will docker containers expose only 80 ?

Is the process running inside the container set up to listen on both ports? If you explicitly docker run -p32769:8080 then it would forward inbound connections from the host port 32769 to port 8080 in the container, but it doesn’t specifically cause processes in the container to respond to that.

I assume you can expose any TCP port number from 1 to 65535 (and as noted above it’s pretty meaningless to do so except for future human maintainers).

Is the process running inside the container set up to listen on both ports?

–> No just I am spinning container with dockerfile in hostmachine (All expose cmnds in dockerfile). no special setup is made inside container