Introduction Docker containers that cannot bind to their specified host ports fail to start with "port is already allocated" errors. This blocks deployments when port conflicts exist with other services or containers.

Symptoms - `docker run -p 8080:8080` returns: "driver failed programming external connectivity: port is already allocated" - Docker Compose: "Bind for 0.0.0.0:8080 failed: port is already allocated" - Error: "address already in use" - Only some containers fail while others bind successfully

Common Causes - Another container already using the host port - System service listening on the same port - Previous container not fully stopped (zombie port binding) - Docker proxy process (docker-proxy) stuck - Port range exhausted (all high ports in use)

Step-by-Step Fix 1. **Find what is using the port**: ```bash sudo lsof -i :8080 sudo ss -tlnp | grep 8080 sudo netstat -tlnp | grep 8080 ```

  1. 1.Check for stuck Docker containers:
  2. 2.```bash
  3. 3.docker ps -a --filter "publish=8080"
  4. 4.docker ps -q | xargs -I {} docker inspect --format '{{.Name}} {{.HostConfig.PortBindings}}' {}
  5. 5.`
  6. 6.Kill the conflicting process or container:
  7. 7.```bash
  8. 8.# Kill the process
  9. 9.sudo kill -9 $(sudo lsof -t -i:8080)
  10. 10.# Or stop the container
  11. 11.docker stop <container-using-port>
  12. 12.docker rm <container-using-port>
  13. 13.`
  14. 14.Restart Docker to clear stuck port bindings:
  15. 15.```bash
  16. 16.systemctl restart docker
  17. 17.`
  18. 18.Use alternative port mapping:
  19. 19.```bash
  20. 20.docker run -p 8081:8080 my-app
  21. 21.# Or let Docker assign a random port
  22. 22.docker run -p 8080 my-app # Docker picks a random host port
  23. 23.`

Prevention - Use dynamic port assignment in development (-P flag) - Implement port conflict detection in deployment scripts - Use service mesh for service-to-service communication instead of host ports - Document port allocations in the team - Use different port ranges for different environments