Skip to content
Lesson: Docker Port MappingSwitch
← DevOps Operations

Delivery and containers

Docker Port Mapping

Publish container ports so that you and others can reach services running in Docker.

A service inside a container listens on the container's own network. On the default bridge network, other computers cannot reach it until you publish a port on the host. For port basics, see the networking guide.

Publish with -p

$ docker run -d --name web -p 8080:80 nginx
$ curl -I http://localhost:8080
HTTP/1.1 200 OK

Read 8080:80 as host port first, container port second. Requests to port 8080 on your machine are forwarded to port 80 in the container.

Several containers can all listen on port 80 internally, but each needs a different host port:

$ docker run -d --name web2 -p 8081:80 nginx

Reusing a busy host port fails with an error saying the port is already allocated.

Choose the address

Without an IP address, a published port is open on all host interfaces, so other machines may be able to connect. To keep it local:

$ docker run -d -p 127.0.0.1:8082:80 nginx

Docker Engine releases before 28.0.0 had a gap: machines on the same local network could still reach a port published to 127.0.0.1.

On Linux, Docker adds its own firewall rules, and published ports can bypass rules you set with tools such as ufw. Do not assume your usual firewall setup protects them.

For UDP, add the protocol, as in -p 5353:53/udp. TCP is the default.

See the mappings

$ docker port web
80/tcp -> 0.0.0.0:8080
80/tcp -> [::]:8080

The IPv6 line depends on your setup. docker ps shows mappings too.

EXPOSE and -P

EXPOSE 80 in a Dockerfile documents which port the application uses. It does not publish anything. -P (capital) publishes all exposed ports to random free host ports:

$ docker run -d -P --name web3 nginx
$ docker port web3
80/tcp -> 0.0.0.0:32768

You set mappings when a container is created. To change them, remove the container and run a new one.

The application must also listen on the right address inside the container. Make it listen on 0.0.0.0.

Try it

Run two nginx containers on host ports 8080 and 8081, test both with curl, check docker port, then remove them.

Check your understanding

Docker Port Mapping

All 4 sections · no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.