问题
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?
回答1:
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
回答2:
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!
回答3:
This saved me a lot of time:
pkill node
回答4:
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
来源:https://stackoverflow.com/questions/13129464/how-to-find-out-which-node-js-pid-is-running-on-which-port