AcademyContainment Breach: The Architect's ShipZone 4: Subterranean Networks

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 |

booting...

Mission Objective

Open the gates:

  1. Map a port: Run docker run -d --name web -p 8080:80 nginx to expose Nginx.
  2. Test it: Run curl http://localhost:8080 to access the server.
  3. Verify: Run docker port web to see the mapping.

Mission Control

Run Nginx with port mapping

Expected Command

docker run -d --name web -p 8080:80 nginx

Test the web server

View port mappings