How to Fix "Address already in use – bind(2) for “127.0.0.1” port 3000 (Errno::EADDRINUSE)"
Trying to start your Rails server, but getting no beans?
If the error message you're getting is
Address already in use – bind(2) for “127.0.0.1” port 3000 (Errno::EADDRINUSE), the fix is pretty easy.
It means you still have a server running, though it may be hanging or stuck in a loop.
I usually run into this if I close the terminal window that's running my local Rails server.
How to Find and Stop a Rails Process
It's a quick 2 step process - get the process ID, then stop it.
Step 1: Get the Process ID of Your Local Rails Server
Let's identify the process ID of the local server, we know it's probably running on port 3000 so we can filter on that:
lsof -wni tcp:3000
The output will look something like this:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME ruby 28120 admin 13u IPv4 0xcaa99f29c9960fd5 0t0 TCP 127.0.0.1:hbci (LISTEN) ruby 28120 admin 14u IPv6 0xcaa99f29c9960fd5 0t0 TCP [::1]:hbci (LISTEN) ruby 28120 admin 31u IPv6 0xcaa99f29c9960fd5 0t0 TCP [::1]:hbci->[::1]:62247 (CLOSE_WAIT) ruby 28120 admin 36u IPv6 0xcaa99f29c9960fd5 0t0 TCP [::1]:hbci->[::1]:62957 (ESTABLISHED) ruby 28120 admin 37u IPv6 0xcaa99f29c9960fd5 0t0 TCP [::1]:hbci->[::1]:62467 (CLOSE_WAIT) Brave\x20 97269 admin 41u IPv6 0xcaa99f29c9960fd5 0t0 TCP [::1]:62957->[::1]:hbci (ESTABLISHED)
We want the
PID value here, that's going to be our Process ID. It lets us identify the hanging Rails server so we can stop it.
Step 2: Stop the Process
Take the PID you got from the first command and run
kill -9 <your PID>. My PID was 28120 so I ran this command:
kill -9 28120
If you don't get any output, that's good. That means it worked!
If you rerun the command you can verify there are no more processes with that PID running:
-bash: kill: (28120) - No such process
A server is already running
When you try to start multiple Rails servers, you'll run into the error message "a server is already running".
This happens either because you already started a server or because Rails was closed in a bad state.
Normally when you spin down your local server it goes through a series of steps to clean up after itself. But force quitting or your computer running out of battery can sometimes cause issues the next time you try to spin your local development environment.
The above steps help clean up your running processes, but you might have to manually delete your
server.pid file. That's one of the things Rails normally does when it stops running but didn't get a chance last time for whatever reason.
This is an annoying issue that happens infrequently enough that I always have to do a quick search to remember the commands.
Hopefully, this helps you next time!