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

2019-02-09 04:19发布

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?

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-09 04:25

This saved me a lot of time:

pkill node

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-09 04:27

Why not a simple fuser based solution?

If you don't care about whether the process using port 3000 is node, it could be as simple as

fuser -k -n tcp 3000

If you wan't to be sure you don't kill other processes, you could go with something like

PID="$(fuser -n tcp 3000 2>/dev/null)" \
  test "node"="$(ps -p $PID -o comm=)" && kill $PID
查看更多
4楼-- · 2019-02-09 04:31

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
查看更多
仙女界的扛把子
5楼-- · 2019-02-09 04:48

A one-liner is

lsof -n -i:5000 | grep LISTEN | awk '{ print $2 }' | uniq | xargs -r kill -9 

You only need the sudo if you are killing a process your user didn't start. If your user started the node process, you can probably kill it w/o sudo.

Good luck!

查看更多
登录 后发表回答