Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

Tags:

docker

port

People also ask

What does port is already allocated mean?

Docker error port is already allocated occurs when there is already a container is running on the same port on which we want to run a new process.

What is port binding in Docker?

The -P command opens every port the container exposes. Docker identifies every port the Dockerfile exposes and the ones that are exposed with the Docker container build --expose parameter. Every exposed port is bound directly on a “random” port of the host machine.

Can two Docker containers use the same port?

Surprisingly or not, neither Docker nor Podman support exposing multiple containers on the same host's port right out of the box. Example: docker-compose failing scenario with "Service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash."


You need to make sure that the previous container you launched is killed, before launching a new one that uses the same port.

docker container ls
docker rm -f <container-name>

Paying tribute to IgorBeaz, you need to stop running the current container. For that you are going to know current CONTAINER ID:

$ docker container ls

You get something like:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
12a32e8928ef        friendlyhello       "python app.py"     51 seconds ago      Up 50 seconds       0.0.0.0:4000->80/tcp   romantic_tesla   

Then you stop the container by:

$ docker stop 12a32e8928ef

Finally you try to do what you wanted to do, for example:

$ docker run -p 4000:80 friendlyhello

I tried all the above answers, none of them worked, in my case even docker container ls doesn't show any container running. It looks like the problem is due to the fact that the docker proxy is still using ports although there are no containers running. In my case I was using ubuntu. Here's what I tried and got the problem solved, just run the following two commands:

sudo service docker stop
sudo rm -f /var/lib/docker/network/files/local-kv.db

I solved it this way:

First, I stopped all running containers:

docker-compose down

Then I executed a lsof command to find the process using the port (for me it was port 9000)

sudo lsof -i -P -n | grep 9000

Finally, I "killed" the process (in my case, it was a VSCode extension):

kill -9 <process id>

The quick fix is ​​a just restart docker:

  1. sudo service docker stop
  2. sudo service docker start