Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash command to return a free port

Tags:

bash

docker

As part of a build pipeline I would like to start containers with a free port.

Looking for something like this:

docker run --name frontend -p $(gimme-a-free-port):80 frontend:latest
like image 699
raitisd Avatar asked May 10 '26 09:05

raitisd


1 Answers

You can use port 0. Applications pass 0 to kernel and kernel assigns unused port to the application.

docker run --name frontend -p 0:80 frontend:latest

Or:

docker run --name frontend -p 80 frontend:latest

In second example I'm just specifying container port, Host port will be assigned automatically.

To verify:

docker port <containerid or container name>
80/tcp -> 0.0.0.0:32768

To get the random port value only:

docker inspect -f '{{ (index (index .NetworkSettings.Ports "80/tcp") 0).HostPort }}' <containerid or container name>
32768
like image 77
Farhad Farahi Avatar answered May 14 '26 01:05

Farhad Farahi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!