Publishing Ports

Use the -p flag to map a port on your host to a port inside the container so you can reach the app.

Syntaxdocker run -p HOST_PORT:CONTAINER_PORT IMAGE

By default, a container's ports are only reachable from inside Docker's network. To access a service from your host or the outside world, you publish a port.

The -p syntax

The flag reads -p HOST:CONTAINER. For example, -p 8080:80 forwards traffic from port 8080 on your machine to port 80 inside the container.

Handy variations

  • -p 80:80 — same port on host and container.
  • -p 127.0.0.1:8080:80 — bind only to localhost.
  • -P — publish all exposed ports to random host ports.

Example

Example · bash
# Map host port 8080 to container port 80
docker run -d -p 8080:80 --name web nginx

# Check which ports are mapped
docker port web
# 80/tcp -> 0.0.0.0:8080

When to use it

  • A developer maps host port 8080 to container port 80 so they can access an Nginx container from their browser at localhost:8080.
  • A team runs multiple microservices locally by mapping each to a different host port (3001, 3002, 3003) while all listen on port 3000 inside their containers.
  • An ops engineer uses -p 127.0.0.1:5432:5432 to expose a database port only on localhost and not on the public network interface.

More examples

Map a single port

Forwards requests on host port 8080 to port 80 inside the Nginx container.

Example · bash
docker run -d -p 8080:80 nginx
curl http://localhost:8080

Bind to specific host address

Restricts the exposed port to the loopback interface so the database cannot be reached from outside the machine.

Example · bash
# Only accessible from localhost, not external interfaces
docker run -d \
  -p 127.0.0.1:5432:5432 \
  -e POSTGRES_PASSWORD=secret \
  postgres:16-alpine

Map multiple ports

Publishes both HTTP and HTTPS ports from a single container using multiple -p flags.

Example · bash
docker run -d \
  -p 80:80 \
  -p 443:443 \
  --name proxy \
  nginx

Discussion

  • Be the first to comment on this lesson.