Summary - Port mapping
- Docker & Kubernetes course
- Beginner
- Lesson 48/82
- 5 min
Combine port mapping options to publish a web server.
Summary: port mapping
In this group:
- Container ports don't open to the outside by themselves; they are published with
-p host:container. - The left side is the host, the right side the container; a host port can be published to only one place.
- Several
-pflags, ranges and/udpare supported. -p 80and-Ppick a random host port;docker portshows the chosen one.127.0.0.1:opens it only to local access; ports that aren't needed are not published at all.
docker run -d -p 80:80 -p 443:443 nginx
docker run -d -p 127.0.0.1:5432:5432 postgres:16Practice Web and a local database
Write two commands: start a container named web from nginx in the background, publishing ports 80 and 443 with the same numbers; start a container named db from postgres:16 in the background with POSTGRES_PASSWORD=gizli, publishing 5432 only on 127.0.0.1.
Starter code
# buraya yazSample solution
docker run -d --name web -p 80:80 -p 443:443 nginx
docker run -d --name db -e POSTGRES_PASSWORD=gizli -p 127.0.0.1:5432:5432 postgres:16Expected output
1f2e3d4c5b6a 2e3d4c5b6a7f
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In docker run -p 8080:3000 img, which port must the application listen on inside the container?
- Both
- 3000 Correct answer
- 8080
- 80
Explanation: The right side is the container port.
2 Publish all EXPOSEd ports.
docker run -d ____ api:1.0
docker run -d -P api:1.0
Explanation: -P picks random ports.
3 Match.
| Term | Meaning |
|---|---|
-p 8080:80 |
Fixed mapping |
-P |
Random, all EXPOSE |
127.0.0.1: |
Local binding |
docker port |
Show mappings |