Docker port mapping (-p) Explained

What Docker port mapping (-p) does, with an example.

Published November 10, 2026

The -p flag publishes a container port on the host: -p HOST:CONTAINER. It maps traffic arriving at a host port to a port inside the container.

How it works

Only published ports are reachable from outside the host. Bind to 127.0.0.1 to keep a service local: -p 127.0.0.1:5432:5432.

EXPOSE in a Dockerfile is documentation only; it does not publish ports.

Try it

docker run -d -p 8080:80 nginx
curl localhost:8080
Welcome to nginx!

Practical examples

Host 8080 → container 80

docker run -d -p 8080:80 nginx

Local only

docker run -d -p 127.0.0.1:5432:5432 postgres

Random host port

docker run -d -P nginx
docker port <container>

Compose

ports:
  - "8080:80"

Common mistakes

  • Publishing databases to the whole internet.
  • Confusing host and container order.
  • Conflicting host ports.

Key takeaways

  • The -p flag publishes a container port on the host: -p HOST:CONTAINER.
  • Run docker <command> --help for all options.
  • Clean up unused resources regularly.

FAQ

EXPOSE vs -p?

EXPOSE documents; -p actually publishes.

Where can I see all options?

Run the command with --help.

More General articles