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.