🐳 Docker Beginner

What is the difference between EXPOSE and port publishing in Docker?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Docker development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

EXPOSE in Dockerfile is a documentation instruction — it declares which ports the container's application listens on, but it does NOT actually make those ports accessible from outside the container. Example: EXPOSE 3000 tells Docker and humans "this container listens on port 3000." It does not affect networking. Port publishing (-p in docker run or ports: in Compose) actually maps a container port to a host port, making it accessible from outside. Two forms: (1) -p 8080:3000 — maps host port 8080 to container port 3000 (binds to all host interfaces: 0.0.0.0); (2) -p 127.0.0.1:8080:3000 — binds only to localhost (more secure — not accessible from other machines). -p 3000 (without host port) — Docker assigns a random available host port. Why EXPOSE at all? (1) Documentation for developers reading the Dockerfile; (2) Used by docker run -P (capital P) which automatically publishes all EXPOSEd ports to random host ports; (3) Some container platforms use it for service discovery. Best practice: always EXPOSE the port in Dockerfile for documentation, and use -p or ports in Compose to control actual access. For services that should only be accessed by other containers (not externally), omit port publishing — use Docker networks instead.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Docker answers easy to follow.