Find the ID of a process running on a given port

macOS
linux

You know how you sometimes forget to stop a local dev server before shutting down VS Code? And then next time you try to fire up that same local server your operating system tells you that a process is already running on that port?

Note: This works on Unix-like systems (macOS, linux); I'm not sure about Windows.

Here's how you can find out the ID of the process. This example assumes that it's port 3000 that youre interested in:

$ lsof -n -i :3000 | grep LISTEN

That will output something similar to this:

$ node 1804 matt 26u IPv4 0x6ecbbd1d5ddec719 0t0 TCP *:redwood-broker (LISTEN)

This tells us that port 3000 is running a node process with the ID 1804.

To kill the process with an ID of 1804:

$ kill 1804

And port 3000 is now free.