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.
Syntax
docker run -p HOST_PORT:CONTAINER_PORT IMAGEBy 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
# 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:8080When 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.
docker run -d -p 8080:80 nginx
curl http://localhost:8080Bind to specific host address
Restricts the exposed port to the loopback interface so the database cannot be reached from outside the machine.
# Only accessible from localhost, not external interfaces
docker run -d \
-p 127.0.0.1:5432:5432 \
-e POSTGRES_PASSWORD=secret \
postgres:16-alpineMap multiple ports
Publishes both HTTP and HTTPS ports from a single container using multiple -p flags.
docker run -d \
-p 80:80 \
-p 443:443 \
--name proxy \
nginx
Discussion