Lesson 2: The Port Authority (Port Mapping)
A container's network is isolated — nobody outside Docker can reach it. To make a containerized service accessible, you need to map a port from the container to the host. This is like opening a gate in the wall.
Port Mapping: -p
docker run -d -p HOST_PORT:CONTAINER_PORT image
# Example: Map host port 8080 → container port 80
docker run -d -p 8080:80 nginx
Host Machine
┌────────────────────┐
│ │
Browser ────│──→ :8080 ─────┐ │
│ │ │
│ ┌───────────▼───────┐
│ │ Container (nginx)│
│ │ listening on :80 │
│ └───────────────────┘
│ │
└────────────────────┘
Now http://localhost:8080 reaches the Nginx container!
Port Mapping Variations
# Map specific port
docker run -d -p 8080:80 nginx
# Map multiple ports
docker run -d -p 8080:80 -p 8443:443 nginx
# Map to a specific host interface
docker run -d -p 127.0.0.1:8080:80 nginx # Only localhost
# Let Docker pick a random host port
docker run -d -p 80 nginx # Docker assigns a port
docker run -d -P nginx # Map ALL exposed ports randomly
Viewing Port Mappings
docker port web
# 80/tcp -> 0.0.0.0:8080
docker ps
# PORTS: 0.0.0.0:8080->80/tcp
EXPOSE vs. -p
These are often confused:
| | EXPOSE (Dockerfile) | -p (Runtime) |
|---|----------------------|----------------|
| What | Documentation only | Actually opens the port |
| When | Build time | Run time |
| Effect | No real networking change | Creates port mapping |
# In Dockerfile - just documentation
EXPOSE 80
# At runtime - actually maps the port
docker run -p 8080:80 nginx
Common Port Mappings for DevOps
| Service | Container Port | Common Host Port | |---------|---------------|-----------------| | Nginx/Apache | 80, 443 | 8080, 8443 | | Node.js | 3000 | 3000 | | PostgreSQL | 5432 | 5432 | | Redis | 6379 | 6379 | | MySQL | 3306 | 3306 | | Grafana | 3000 | 3001 |
Mission Objective
Open the gates:
- Map a port: Run
docker run -d --name web -p 8080:80 nginxto expose Nginx. - Test it: Run
curl http://localhost:8080to access the server. - Verify: Run
docker port webto see the mapping.