Skip to content

port is already allocated: Docker Compose finds the port taken

Containertested on Docker 29.9.0, Docker Compose 5.6.0

Docker can give out a host port only once. If another container already holds it, the first up fails. The second up is the dangerous one: it starts the already created container without publishing the port, reports “Healthy” – and a different service answers on the port.

Symptom

docker compose up -d --wait; echo "Exit: $?"
Error response from daemon: failed to set up container networking: driver failed
programming external connectivity on endpoint notes-api-1 (…): Bind for
127.0.0.1:8080 failed: port is already allocated
Exit: 1

On the second run everything is green, but docker compose ps shows only 8080/tcp for api, without an arrow – nothing is published. The answer on localhost:8080 comes from the other container.

Diagnosis

Find the owner of the port and look at your own port lines.

docker ps --filter publish=8080 --format '{{.Names}}  {{.Ports}}'
grep -nE '^ +- "[0-9]+:' compose.yaml
notes-blocker  127.0.0.1:8080->80/tcp
22:      - "8080:8080"
76:      - "3000:3000"

Causes

publish=8080Another container holds the port

Here notes-blocker holds 127.0.0.1:8080. Docker hands out a host port only once per address.

"8080:8080"A port without an IP means all interfaces

Without an IP before the first colon Docker binds to 0.0.0.0 and :: – the service is reachable from the whole network, not just locally.

second up--wait checks health, not reachability

The second up starts the container created the first time, without publishing the port. It is healthy but not reachable from outside.

Fix

Make the port a variable with a default, bound only to 127.0.0.1; set the value per machine in .env.
sed -i '' -e 's#"8080:8080"#"127.0.0.1:${API_PORT:-8080}:8080"#' \
  -e 's#"3000:3000"#"127.0.0.1:${WEB_PORT:-3000}:3000"#' compose.yaml
printf '\nAPI_PORT=8081\n' >> .env
docker compose up -d --wait; echo "Exit: $?"
docker compose ps --format 'table {{.Service}}\t{{.Ports}}'
api       127.0.0.1:8081->8080/tcp
web       127.0.0.1:3000->3000/tcp

Don't: Simply stop the other container without knowing who owns it – or publish ports without an IP just because it then “works”.

▶
Break it yourself and find it – free
Docker Compose hands-on, Day 15: repair ten broken Compose stacks against the clock.
Go to day 15 →

FAQ

How do I see in docker compose ps that a port is not published?

In the PORTS column – if it only shows 8080/tcp without an arrow (->), the port is only open inside the container.

Why a variable for the port?

With ${API_PORT:-8080} every machine sets its port in .env without changing compose.yaml.

Related error patterns

More