When working with Node.js, I occasionally stumble upon "Port is already in use" or "Port is already allocated" when a previous process failed to clean up successfully when closed. (Nuxt, looking at you! 👀)
This is a bit annoying when your node application fails to spawn the local dev server. Requiring your attention to identify why a port is still open.
The Easiest Solution?
Turn your computer off and on again. (seriously)
But for a more elegant solution, read on for more elegant ways of dealing with this issue.
Finding the Culprit
You can use the "list open files" command, as everything is regarded as a file in UNIX-based operating systems. lsof
and use it to list any processes listening on the corresponding port. (port 3000 in the below example).
The -i
will show all processes that are associated with the network, such as ports.
$ sudo lsof -i:3000
Running the command will give you a list of processes running. Take note of the PID as this is what you will need to kill the process in a moment.
Killing the Process
Once you have identified the process that you wish to kill, refer to the PID and replace the below "PID" together with the kill
command (-9 sends a SIGKILL signal).
$ sudo kill -9 PID
And that's it. You should be able to rerun your process and listen on your intended port again.