C.W.K.
Stream
Lesson 03 of 05 · published

Port Mapping — Host:Container, Bind Address, Random

~12 min · commands, networking

Level 0Container Curious
0 XP0/36 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Why your container is unreachable

Containers have their own network namespace. Their ports are not on the host's network until you explicitly map them. EXPOSE in a Dockerfile is documentation only — it does not publish anything.

The -p syntax

-p [HOST_IP:]HOST_PORT:CONTAINER_PORT[/PROTOCOL]
  • -p 8080:80 — host 8080 → container 80 (TCP, all interfaces)
  • -p 127.0.0.1:8080:80 — bind to loopback only (not exposed to LAN)
  • -p 8080:80/udp — UDP instead of TCP
  • -p 80 — random host port. Find it with docker port.

The order is HOST:CONTAINER

This trips everyone. -p 8080:80 means "hit my laptop on 8080 and you reach the container's 80." Reverse it and your hopes are also reversed.

Code

Common port patterns·bash
# Map one port (HTTP)
docker run -d -p 8080:80 nginx:1.27-alpine
curl http://localhost:8080

# Map both HTTP and HTTPS
docker run -d -p 8080:80 -p 8443:443 nginx:1.27-alpine

# Bind to loopback only — not reachable from the LAN
docker run -d -p 127.0.0.1:8080:80 nginx:1.27-alpine

# Let Docker pick a host port (handy for parallel test envs)
docker run -d -p 80 --name web nginx:1.27-alpine
docker port web
# 80/tcp -> 0.0.0.0:55012

External links

Exercise

Run two nginx containers on host ports 8081 and 8082, both bound to 127.0.0.1 only. Verify with curl from your machine, then verify from another machine on your LAN that they are NOT reachable. Capture the commands and the curl results.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.