Docker Community Forums

Share and learn in the Docker community.

Is it possible to keep the random assigned port when restarting containers?

docker

(Dennis Andersson) #1

Hello,

I havent seen this asked, I want to check if there is a way to keep the random assigned port when creating a container.

Example:

docker run -t -p 8080 --name test ubuntu bash

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b7045f194a77 ubuntu “bash” 22 seconds ago Up 1 seconds 0.0.0.0:32772->8080/tcp test

docker restart test

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b7045f194a77 ubuntu “bash” 4 minutes ago Up 2 seconds 0.0.0.0:32773->8080/tcp test

Best regards
//Dennis


(Kylesoskin) #2

You could make a function in your .bashrc to do it for you. Something like:

function docker_restart_same_port() {
port=$(docker port $1 8080 | awk -F: ‘{print $NF}’)
docker rm -f $1
docker run -t -p $port:8080 --name $1 ubuntu bash
}

And then to restart it just do “docker_restart_same_port test” and that would work.
This however removes, and then recreates it with a new port, not just restarts it.

But as far as a built in docker flag to do it, I don’t think that exists.

The other option is to specify it on creation, then it will stay the same through restarts.

Meaning something just like ‘docker run -p 34567:8080 ubuntu bash’ can be restarted all the time and the port will remain set. Also try doing -p 0:8080. I think that might pick a random port and set it permanently, rather than randomly picking one each restart… Not sure if I’m remembering that correctly though.


(Dennis Andersson) #3

Thanks for the reply, and the script.

I tried “-p 0:8080” but it still changed the port after restart. A native docker feature like that would be nice to have since I then could give developers SFTP access and deploy-servers ssh access to the containers and volumes. The reason why I want a built in way to do it is because we are creating the containers through the API.


(Kylesoskin) #4

I agree that it would be a nice feature to have. How I have gotten around it before is the recreation method as above, or hard coding it to a specific port and each developer just knowing that is their assigned port (developer1 = 33001, developer2 = 33002, etc…). Another thing you could do is after the restart through the api, just make a second api request for the containers new port information and return that. So if it is the developer doing the restart, the new port is displayed back to him after. But as far as it being built in, no luck :frowning: