Docker Community Forums

Share and learn in the Docker community.

Is it possible to avoid random ports using docker run -P?

Hello all,
I have a dockerfile which exposes a port:
EXPOSE 4101/tcp

I run the image using the following command:
docker run -d -P someImage

Now I was reading through the documentation and saw that -P maps exposed ports from the container to random ports on the host machine.
This behavior might not be suitable for me as I have a very specific range of ports open on the host machine (say, 4000 to 4200).

I am aware there’s also -p option, but this might not be suitable as well since I do not necessarily know the exposed port when I come to run the container (only during image build).

So my question is, is there a way to map all exposed ports to their coresponding host ports?
For example I would expect that port 4101 from the container would be exposed to port 4101 on the host.

Thanks for the help! :slight_smile:

Well I went with the following option eventually, seems like the best way for me:
network_mode: host

What it does is using the host network instead of creating a separated network for the container, so ports are immediately taken on the host.