Expose vs Publish Ports
EXPOSE in a Dockerfile names a port, and -p on the command line publishes one. EXPOSE is a note, and -p opens the door.
EXPOSE in the Dockerfile
This line notes that the app listens on port 80.
FROM nginx:1.27-alpine
EXPOSE 80Publish with -p
This command publishes container port 80 on host port 8101.
docker run -d --name g5-web -p 8101:80 nginx:1.27-alpineSee the mapping
The ports column shows the mapping in the listing.
docker ps --format "{{.Names}} {{.Ports}}"Example
docker run -d --name g5-web -p 8101:80 nginx:1.27-alpine >/dev/null
docker ps --format "{{.Names}} {{.Ports}}"
curl -s http://localhost:8101/ | head -3Key points
- EXPOSE: a Dockerfile note that names the port the app listens on.
- EXPOSE alone opens nothing. The port stays inside the container.
- -p host:container publishes a container port on the host.
- Use -p when the app must answer on the host, like a web server.
- Skip -p when only other containers need the port, on one network.
In this example, nginx runs with its port published on the host. The listing shows the mapping from host port 8101 to container port 80. curl fetches the page through the mapping. The page proves -p opened the door that EXPOSE only described.
Note
A published port answers on the host. An exposed port only documents the intent.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does EXPOSE do on its own?