Docker NetworkingLesson 3.3
Port mapping and exposing containers to the host
docker run -p, host port, container port, EXPOSE instruction, 0.0.0.0 binding, localhost binding, multiple port mappings
Bridging Container Ports to Your Host
A running container's ports are invisible to the host unless you explicitly map them using -p. The format is -p HOST_PORT:CONTAINER_PORT.
Basic Port Mapping
# Map host 8080 to container 80
docker run -d -p 8080:80 nginx
# Map multiple ports
docker run -d -p 3000:3000 -p 9229:9229 my-node-app
# Bind to a specific host interface (restrict to localhost only)
docker run -d -p 127.0.0.1:5432:5432 postgres:16
# Let Docker assign a random available host port
docker run -d -p 5432 postgres:16
docker port container-id # See what port was assigned
EXPOSE vs -p
The EXPOSE instruction in a Dockerfile is documentation — it tells other developers and tools which port the app listens on. It does not publish the port to the host. You must use -p at runtime to actually make the port reachable.
Security Note
By default, -p 5432:5432 binds to 0.0.0.0 — all network interfaces — making the container reachable from other machines on the network. For databases, always use 127.0.0.1:5432:5432 to restrict access to the local machine only.
