What is the difference between "expose" and "publish" in Docker?

Better Stack Team
Updated on April 7, 2023

In Docker, "expose" and "publish" are two related but distinct concepts that are used to control network access to containers.

The "expose" instruction is used in a Dockerfile to specify which ports the container should listen on for incoming connections. For example, the following Dockerfile excerpt exposes port 80 for HTTP traffic:

 
FROM nginx
EXPOSE 80

Note that the "expose" instruction does not actually open any ports on the container's network interface, nor does it create any network mappings. Instead, it simply documents which ports the container is designed to use.

The "publish" option, on the other hand, is used with the "docker run" command to create a network mapping between a port on the host system and a port exposed by the container. For example, the following command runs a container based on the nginx image and publishes port 8080 on the host system to port 80 in the container:

 
docker run -p 8080:80 nginx

This allows the container to receive incoming traffic on port 8080 from the host system's network interface, and forward it to port 80 inside the container.

So, in summary, "expose" is used to declare which ports a container listens on, while "publish" is used to create a network mapping between a port on the host system and a port exposed by the container.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack