How to Expose Port in Docker: Simple Guide with Examples
To expose a port in Docker, use the
-p option with docker run to map a container port to a host port, like docker run -p 8080:80. You can also declare ports in a Dockerfile using the EXPOSE instruction, which documents the ports but does not publish them automatically.Syntax
The main way to expose ports in Docker is by using the -p flag with docker run. The syntax is:
-p <host_port>:<container_port>: Maps a port on your computer (host) to a port inside the container.EXPOSE <container_port>in Dockerfile: Declares which ports the container listens on, but does not publish them.
bash
docker run -p <host_port>:<container_port> <image_name> # Example Dockerfile line: EXPOSE <container_port>
Example
This example runs an Nginx web server container and exposes port 80 inside the container to port 8080 on your host machine. You can then access the web server at http://localhost:8080.
bash
docker run -d -p 8080:80 nginx
Output
a1b2c3d4e5f6g7h8i9j0
# Container runs in background with port 80 exposed to host port 8080
Common Pitfalls
Common mistakes when exposing ports in Docker include:
- Using
EXPOSEin Dockerfile but not publishing ports with-p, so ports are not accessible from the host. - Mapping the wrong ports or forgetting to map ports, causing connection failures.
- Trying to use the same host port for multiple containers, which causes conflicts.
Correct usage example:
bash
# Wrong: EXPOSE only (no port published) # Dockerfile EXPOSE 80 # Running container without -p docker run nginx # Right: publish port with -p docker run -p 8080:80 nginx
Quick Reference
| Command | Description |
|---|---|
| docker run -p 8080:80 nginx | Run container mapping host port 8080 to container port 80 |
| EXPOSE 80 | Declare port 80 in Dockerfile (does not publish) |
| docker ps | List running containers and their port mappings |
| docker stop | Stop a running container |
Key Takeaways
Use
-p host_port:container_port with docker run to expose ports to your host.EXPOSE in Dockerfile only documents ports; it does not publish them automatically.Avoid port conflicts by not mapping the same host port to multiple containers.
Check running containers' port mappings with
docker ps.Always verify the correct ports are mapped to access your container services.