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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github