Fix Docker Error: Failed Port Allocation
5/6/2019
When attempting to run a Docker container with docker container run ...
, you may see this error:
Bind for 0.0.0.0:8000 failed: port is already allocated
Whenever you see this error, it means that the container is unable to bind the container's exposed port to the port on the host machine.
Solution
This is an easy fix with two steps:
-
run
lsof -i :8000
(replace8000
with the port that's allocated in your error).lsof -i :8000 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME com.docke 1596 chaseadamsio 20u IPv4 0x677313baaeffcfd7 0t0 TCP *:irdmi (LISTEN) com.docke 1596 chaseadamsio 21u IPv6 0x677313ba9b203357 0t0 TCP localhost:irdmi (LISTEN)
If the output has
COMMAND
ofcom.docker
(as above), proceed to step 2.lsof -i :8000 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME node 46205 chaseadamsio 19u IPv4 0x677313ba9d523357 0t0 TCP localhost:irdmi (LISTEN)
If the output has
COMMAND
that's anything else, make a note of thePID
for the process serving on that port and proceed to step 3. -
run
docker ps
to get a list of running containers.docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 20c6837d446e crccheck/hello-world "/bin/sh -c 'trap \"eā¦" 4 seconds ago Up 3 seconds (health: starting) 0.0.0.0:8000->8000/tcp web-test
Under
PORT
you'll see a mapping of theHOST PORT
(0.0.0.0:8000) ->CONTAINER PORT
(8000/tcp). The port from your failure will be on one of the containers. Make a note of theCONTAINER ID
and rundocker stop <CONTAINER ID>
. If you no longer need the container, rundocker rm <CONTAINER ID>
to clean it up. -
With the
PID
from step 1 in hand, runps <PID>
to make sure the process serving on that port is okay to kill.If it is, first, check any open Terminal windows to make sure the process isn't running as a part of some other script. If it is,
ctrl-c
to send aSIGINT
. If it isn't running in a Terminal window and you're confident that it's okay to kill, runkill <PID>
. If you're not sure what it is, restart your host machine and see if it restarts. If the process restarts on machine booting, consider running your container on a different port.
After you've gone through the steps above, when you attempt to run docker container run...
you should make it a little further through starting up your container.