The -p flag
- Docker & Kubernetes course
- Beginner
- Lesson 44/82
- 4 min
Learn port mapping with the -p flag.
The -p flag
The -p (--publish) form is [host_ip:]host_port:container_port[/protocol]. The left side is the host, the right side is the container; mixing these up is the most common mistake:
docker run -d -p 3000:8080 api:1.0 # localhost:3000 -> container 8080
docker run -d -p 5353:53/udp dns-sunucu # a UDP portPort conflict
A host port can be published to only one container (or process). The second attempt errors; a different host port is chosen:
$ docker run -d -p 8080:80 nginx
$ docker run -d -p 8080:80 nginx
Error: Bind for 0.0.0.0:8080 failed: port is already allocated
$ docker run -d -p 8081:80 nginx # the second copy on 8081Practice Two copies, two ports
Start two containers from the api:1.0 image in the background: api1 maps host port 3000 and api2 host port 3001 to container port 8080.
Starter code
# buraya yazSample solution
docker run -d --name api1 -p 3000:8080 api:1.0
docker run -d --name api2 -p 3001:8080 api:1.0Expected output
b1c2d3e4f5a6 c2d3e4f5a6b7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The application listens on 8080 inside the container and you want to open localhost:3000 in the browser. Which is right?
- --expose 3000
- -p 3000:8080 Correct answer
- -p 8080:3000
- -p 3000
Explanation: The host is on the left, the container on the right.
2 Publish a UDP port.
docker run -d -p 5353:53____ dns-sunucu
docker run -d -p 5353:53/udp dns-sunucu
Explanation: The protocol is appended with a slash; the default is tcp.
3 Match the mappings.
| Term | Meaning |
|---|---|
-p 3000:8080 |
localhost:3000 → 8080 |
-p 8081:80 |
localhost:8081 → 80 |
/udp |
UDP protocol |
port is already allocated |
Host port taken |