Docker Bind for Port Failed: Port is Already Allocated
How to find and terminate processes hogging ports (like 80, 443, or 3306) and fix Docker's bind port allocation errors.
You run docker-compose up or docker run to spin up a container, only to receive a failure message stating that a network port on your host machine is already bound or allocated by another service.
Symptom & Error Signature
The command output will terminate with an error like this:
docker: Error response from daemon: driver failed programming external connectivity on endpoint web-container (a5a8f9c1b...): Bind for 0.0.0.0:80 failed: port is already allocated.
Root Cause Analysis
This error means a service on the host machine (outside of Docker) is already listening on the exact port your container is trying to publish (e.g., port 80 for HTTP, 443 for HTTPS, or 3306 for MySQL).
Common culprits include:
- A local instance of Apache or Nginx running on your host OS.
- A local MySQL or PostgreSQL database instance.
- Another forgotten Docker container running in the background.
Step-by-Step Resolution
1. Identify the Process Using the Port
To find out what process is hogging the port (let’s assume it’s port 80), run the following command on your host:
sudo lsof -i :80
Or, if lsof is not installed, use netstat:
sudo netstat -nlp | grep :80
The output will show the Program Name and its Process ID (PID). For example:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 1204 root 6u IPv4 24351 0t0 TCP *:http (LISTEN)
In this case, a native instance of nginx with PID 1204 is running on the host and using the port.
2. Handle the Conflicting Service
You have two options: stop the host service or change your Docker container’s port mapping.
Option A: Stop/Disable the Host Service
If you do not need the host service running, you can stop it:
# For Apache
sudo systemctl stop apache2
# For Nginx
sudo systemctl stop nginx
To prevent it from starting automatically at boot:
sudo systemctl disable nginx
Option B: Change the Docker Port Mapping
If you need the host service to stay active, change the port mapping of your container.
In a docker-compose.yml file, change the host port (left side of the colon) to something else, like 8080:
services:
web:
image: nginx:alpine
ports:
- "8080:80" # Map host port 8080 to container port 80
Or when running via CLI:
docker run -d -p 8080:80 nginx:alpine
Now you can access the container at http://localhost:8080 instead of port 80.
3. Check for Orphaned Docker Containers
Sometimes, Docker itself is hogging the port because of a container that did not stop correctly. List all running containers:
docker ps
If you see a container using the port, stop it:
docker stop <container_id>
If it refuses to stop, force remove it:
docker rm -f <container_id>
