How to expose ports in Docker?
· Category: Docker
Short answer
Use the -p flag with docker run to map a host port to a container port. The EXPOSE instruction in a Dockerfile documents which ports the container listens on, but does not publish them automatically.
Steps
- Determine the port your application listens on inside the container.
- Map it with
-p HOST:CONTAINERor-p HOST:CONTAINER/PROTOCOL. - Use
-Pto publish all exposed ports to random high-numbered host ports.
Example
docker run -p 8080:80 nginx
Publish to a specific IP:
docker run -p 127.0.0.1:8080:80 nginx
Publish a UDP port:
docker run -p 53:53/udp dns-server
Dockerfile:
EXPOSE 80/tcp
EXPOSE 53/udp
Tips
- Use fixed host ports for predictable access and random ports to avoid conflicts.
- On Linux, ports below 1024 require root privileges.
- Use
docker port <container>to inspect active port mappings.
Common issues
- "Bind for 0.0.0.0:8080 failed" means the host port is already in use.
- Forgetting
-pmeans the port is only accessible inside the container network. - Firewall rules on the host can block external access to published ports.