CodeBlanks Logo Icon CodeBlanks

Random ports

Learn to assign random ports with -P.

Random port

If no host port is written (-p 80), Docker picks a free high port. -P (uppercase) publishes all EXPOSEd ports in the image to random ports:

$ docker run -d --name w1 -p 80 nginx
$ docker port w1
80/tcp -> 0.0.0.0:32768
$ docker run -d --name w2 -P nginx
$ docker port w2
80/tcp -> 0.0.0.0:32769

When is it used?

Random ports are handy for opening many copies of the same service without conflicts (tests, CI). The chosen port is then read with a script:

docker run -d --name test-db -P postgres:16
PORT=$(docker port test-db 5432 | cut -d: -f2)
echo "Bağlantı: localhost:$PORT"

Practice Test database

Write two commands: start a container named test-db from postgres:16 in the background with POSTGRES_PASSWORD=test, publishing all EXPOSEd ports randomly; then show which host port 5432 is mapped to.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker run -d --name test-db -e POSTGRES_PASSWORD=test -P postgres:16
docker port test-db 5432

Expected output

7a8b9c0d1e2f
0.0.0.0:32770

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which ports does the -P flag publish?

  • Only 80
  • None
  • All host ports
  • All ports declared with EXPOSE in the image Correct answer

Explanation: This is a concrete effect of EXPOSE.

2 Publish all EXPOSEd ports randomly.

Question
docker run -d ____ nginx
Answer
docker run -d -P nginx

Explanation: Uppercase P means "publish all".

3 Match.

Term Meaning
-p 80 Random host port
-P All EXPOSE ports
32768 Chosen high port
docker port Find the chosen one

All lessons in Beginner