The EXPOSE and PUBLISH concepts in Docker serve different purposes regarding port management for containers:
EXPOSE
- Purpose: The
EXPOSEinstruction in a Dockerfile is used to indicate which ports the application inside the container will listen on. It serves as documentation and does not actually open the ports for external access. - Usage: It is defined in the Dockerfile and is meant for informational purposes. It helps users understand which ports are intended for use.
- Example:
EXPOSE 80
PUBLISH
- Purpose: The
PUBLISHoption is used when running a container with thedocker runcommand. It actually maps a port on the host machine to a port on the container, allowing external access to the container's services. - Usage: It is specified at runtime and is necessary for making the container's ports accessible from outside the Docker network.
- Example:
In this example, port 80 of the container is mapped to port 8080 on the host.docker run -p 8080:80 my-image
Summary
EXPOSEis for documentation and does not open ports.PUBLISH(using-por--publish) is for mapping container ports to host ports, enabling external access.
