In Docker, the concepts of "expose" and "publish" are frequently discussed. Both pertain to container network port configuration, but their specific purposes and behaviors differ.
-
Expose:
- The
EXPOSEinstruction in Dockerfile is primarily used to specify the ports the container listens on at runtime for documentation purposes. It does not automatically expose the port to the host. - Using
EXPOSEinforms the container user about which ports the container intends to open for communication. However, it is merely a declaration and does not imply external access.
- The
-
Publish:
- When running a container, use the
-por--publishflag to map the container's ports to the host's ports. This enables access to the port from the host or external networks. - For example, using
docker run -p 80:80 nginxmaps the container's port 80 to the host's port 80, allowing the host's port 80 to accept external requests and forward them to the container.
- When running a container, use the
In summary, EXPOSE is a declaration during image building that specifies which ports the container intends to use, while publish is the actual port mapping operation performed when running the container, enabling external access to the specified ports.