Docker Port Mapping with -p Flag
Learn how to expose container ports to the host using Docker's -p flag. Understand port mapping syntax, binding to specific interfaces, and common port configurations for web services.
Detailed Explanation
Exposing Container Ports
By default, container ports are not accessible from the host machine or the outside network. The -p (or --publish) flag maps a container port to a host port, making the service reachable:
docker run -d -p 8080:80 nginx
This maps host port 8080 to container port 80. Visiting http://localhost:8080 on the host reaches the Nginx server inside the container.
Port Mapping Syntax
The -p flag supports several formats:
| Format | Meaning |
|---|---|
-p 8080:80 |
Map host 8080 to container 80 (all interfaces) |
-p 127.0.0.1:8080:80 |
Map only on localhost (not externally accessible) |
-p 8080:80/udp |
Map UDP port (default is TCP) |
-p 8080:80/tcp -p 8080:80/udp |
Map both TCP and UDP |
-p 80 |
Map container port 80 to a random host port |
Binding to Specific Interfaces
By default, -p 8080:80 binds to 0.0.0.0 (all network interfaces), making the port accessible from any IP address that can reach the host. For security, you can restrict binding:
# Only accessible from the host itself
docker run -d -p 127.0.0.1:8080:80 nginx
# Only accessible from a specific network interface
docker run -d -p 192.168.1.100:8080:80 nginx
Multiple Port Mappings
Many applications need multiple ports. Specify -p multiple times:
# Web server with HTTP and HTTPS
docker run -d -p 80:80 -p 443:443 nginx
# Application with web UI and API
docker run -d -p 3000:3000 -p 9090:9090 my-app
Dynamic Port Assignment
Omitting the host port lets Docker choose an available port automatically:
docker run -d -p 80 nginx
Use docker port <container> to discover the assigned port:
docker port my-nginx
# 80/tcp -> 0.0.0.0:49153
Common Port Mappings
| Service | Typical Mapping |
|---|---|
| Nginx/Apache | -p 80:80 -p 443:443 |
| Node.js app | -p 3000:3000 |
| PostgreSQL | -p 5432:5432 |
| Redis | -p 6379:6379 |
| MySQL | -p 3306:3306 |
Security Considerations
- Avoid mapping database ports to
0.0.0.0in production; use Docker networks instead. - Use a reverse proxy (Nginx, Traefik) in front of application containers rather than exposing them directly.
- Firewall rules on the host do not always apply to Docker-mapped ports, as Docker modifies iptables directly.
Use Case
Deploying a web application where Nginx serves static files on port 80 and a Node.js API listens on port 3000, both needing to be accessible from the host network for development and testing.