How to Fix "Port is already allocated" Error in Docker


I’m sure we’ve encountered this error plenty of times, the one that looks like this.

ERROR: for postgres  Cannot start service postgres: driver
failed programming external connectivity on endpoint test_postgres_1
Bind for 0.0.0.0:5432 failed: port is already allocated

In this example, we have another container or an application listening on the port 5432 on our machine. This prevents our service from allocating that port.

Now, how can we fix this?

I was using docker-compose to start and stop my applications, so naturally, I used docker-compose ps to list all running containers and docker-compose down to stop those containers.

However, docker-compose commands only execute on containers related to images in our docker-compose.yml files. We also need to check containers started without docker-compose.

This is the process I would use to stop the correct containers.

First, I would stop all containers started by docker-compose (or just that one container).

docker-compose down

Then, I would list all running containers.

docker container ls -a
CONTAINER ID  IMAGE    ... PORTS                   NAMES
45eec0e12d63  postgres ... 0.0.0.0:5432->5432/tcp  test_postgres_1

Let’s grab the CONTAINER ID and stop/remove the container.

docker stop 45eec0e12d63
docker rm 45eec0e12d63