Publish port

3 snippets in Docker

DKDocker

Port Mapping (-p)

DK · Run Options
Syntax
docker run -p <host_port>:<container_port> <image>
docker run -p <host_ip>:<host_port>:<container_port> <image>
Example
docker run -d -p 8080:3000 myapp:1.0
docker run -d -p 127.0.0.1:5432:5432 postgres:16

Note The format is always host:container. Binding to 127.0.0.1 restricts access to localhost only - critical for databases you do not want exposed on the network. Without an IP, Docker binds to 0.0.0.0 (all interfaces).

Port Mapping in Compose

DK · Docker Compose
Syntax
services:
  api:
    ports:
      - "<host>:<container>"
Example
services:
  api:
    ports:
      - "8080:3000"
      - "127.0.0.1:9229:9229"

Note Always quote port mappings in YAML - values like 80:80 can be misinterpreted as a base-60 number by the YAML parser. Binding debug ports to 127.0.0.1 prevents accidental exposure on the network.

Publishing Ports to the Host

DK · Networking
Syntax
docker run -p <host_port>:<container_port> <image>
docker run -P <image>
Example
docker run -d -p 8080:80 -p 8443:443 nginx:alpine
docker run -d -P nginx:alpine

Note -P (uppercase) publishes ALL exposed ports to random high-numbered host ports - check the mapping with docker port. Docker's port forwarding bypasses iptables/firewall rules on Linux, which can unexpectedly expose services. Use 127.0.0.1:port:port to restrict to localhost.

Frequently asked questions

How does Docker handle publish port?
Docker covers this with 3 copy-ready snippets on this page. The "Port Mapping (-p)" snippet in Docker uses `docker run -p <host_port>:<container_port> <image>`.
Which command does the Docker example use?
The "Port Mapping (-p)" snippet uses `docker run -p <host_port>:<container_port> <image>`, from the Run Options section of the Docker cheat sheet.
What other Docker snippets are shown for "publish port"?
Besides "Port Mapping (-p)", this page also shows "Port Mapping in Compose", "Publishing Ports to the Host".
Is there anything to watch out for?
Yes. For "Port Mapping (-p)": The format is always host:container. Binding to 127.0.0.1 restricts access to localhost only - critical for databases you do not want exposed on the network. Without an IP, Docker binds to 0.0.0.0 (all interfaces).