如何找出哪个 Node.js pid 在哪个端口上运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13129464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:33:41  来源:igfitidea点击:

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

node.jsportkillpid

提问by Pardoner

I'd like to restart one of many Node.js processes I have running on my server. If I run ps ax | grep nodeI 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?

我想重新启动我在服务器上运行的许多 Node.js 进程之一。如果我运行,ps ax | grep node我会得到我所有 Node 进程的列表,但它没有告诉我它们在哪个端口上。我如何杀死在端口 3000 上运行的那个(例如)。管理多个 Node 进程的好方法是什么?

回答by David Weldon

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 5902is the pid. You can use something like this to kill it:

在这种情况下,5902是 pid。你可以使用这样的东西来杀死它:

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

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

这是一个替代版本,使用egrep它可能会好一点,因为它专门搜索字符串“节点”:

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:

您可以将上述内容转换为脚本或将以下内容放入您的~/.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

回答by Naveed Ul Islam

This saved me a lot of time:

这为我节省了很多时间:

pkill node

pkill node

回答by Michael Cole

A one-liner is

单线是

lsof -n -i:5000 | grep LISTEN | awk '{ print  }' | 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.

如果您要终止用户未启动的进程,则只需要 sudo。如果您的用户启动了节点进程,您可以在不使用 sudo 的情况下终止它。

Good luck!

祝你好运!

回答by idrarig

Why not a simple fuserbased solution?

为什么不是基于简单fuser的解决方案?

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

如果不关心使用3000端口的进程是不是node,可以这么简单

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