How to find out which Node.js pid is running on which port

Pardoner picture Pardoner · Oct 29, 2012 · Viewed 35.3k times · Source

I'd like to restart one of many Node.js processes I have running on my server. If I run ps ax | grep node I get a list of all my Node proccesses but it doesn't tell me which port they're on. How do I kill the one running on port 3000 (for instance). What is a good way to manage multiple Node processes?

Answer

David Weldon picture David Weldon · Oct 29, 2012

If you run:

$ netstat -anp 2> /dev/null | grep :3000

You should see something like:

tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      5902/node

In this case the 5902 is the pid. You can use something like this to kill it:

netstat -anp 2> /dev/null | grep :3000 | awk '{ print $7 }' | cut -d'/' -f1 | xargs kill

Here is an alternative version using egrep which may be a little better because it searches specifically for the string 'node':

netstat -anp 2> /dev/null | grep :3000 | egrep -o "[0-9]+/node" | cut -d'/' -f1 | xargs kill

You can turn the above into a script or place the following in your ~/.bashrc:

function smackdown () {
  netstat -anp 2> /dev/null |
  grep :$@ |
  egrep -o "[0-9]+/node" |
  cut -d'/' -f1 |
  xargs kill;
}

and now you can run:

$ smackdown 3000