Docker Community Forums

Share and learn in the Docker community.

EXPOSE in Dockerfile vs docker run -p

When using EXPOSE 8081 in Dockerfile and running the container without the -p option the container is started as


When running the container with docker run -it -p 8081:8081, the container is started as


Is it possible to use EXPOSE in Dockerfile and make the container starts as with the -p option (i.e.>8081/tcp)?

An expose does nothing by itself. It is merley a hint and used by docker run -P (expose all port) or by managent UIs to provide the port mappings duing an assisted creation of the container. Even though it will map all container ports to the host, I am not sure wether it maps them 1:1 or assigns a random host port to each container port.

You don’t have to declare ‘EXPOSE’ for a port to be able to map it. Map whatever container port you want - it is not even required that a process actualy is listening on the container port - as long as the host side port is not occupied by another process. Though, if you want to keep it clean you better start a process that listens on a port and provide a hint about its existance using a EXPOSE declartion.

1 Like

Thanks @meyay for the helpful info.

Using the -P option provides a random host port for each exposed container port rather than the 1:1 mapping.

1 Like

Thank for clarification @dannc! I knew there must be a reason why I never used the -P flag, but I couldn’t remember it ^^