Skip to content
BENIBIX Learn

Container Port Mapping

Infrastructure📦 ContainersContainer Storage and Networking

Also known as Port Publishing, Docker Port Mapping, Publish Port, docker run -p

A link from a host port to a port inside a box. It lets outside traffic in.

Think of it like

Think of it like a phone switchboard. A call to one number is passed to a desk inside.

Example

Jack runs two web apps, each listening on port 80 inside its container. He maps one to host port 8080 and the other to 8081.

Why it matters

Without it, nothing outside the container can reach the app. It is the first thing to check when a page will not load.

Definition

Port mapping connects a port on the host computer to a port inside a container. A container's ports are closed to the outside until you publish them. The flag -p 8080:80 sends traffic for host port 8080 to port 80 in the container. The host port comes first and the container port second. Two containers can both use port 80 inside, as long as each maps to a different host port.

Example code

console
$ docker run -d -p 8080:80 nginx
$ curl -I localhost:8080
HTTP/1.1 200 OK
Host port 8080 now leads to port 80 inside the container, and the web server answers.
Traffic for host port 8080 is passed on to port 80 inside the web container.

Common mistake

Writing the ports the wrong way round. In -p 8080:80, the host port is first and the container port is second.

Key takeaways

  1. 1
    Closed by default. Container ports are shut to the outside.
  2. 2
    Host first. The order is host port, then container port.
  3. 3
    Many apps, one port. Each maps to its own host port.