I have a simple TCP server that listens on a port.
var net = require(\"net\");
var server = net.createServer(function(socket) {
socket.end(\"Hello!\\n\"
You can use fuser to get what you want to be done.
In order to obtain the process ids of the tasks running on a port you can do:
fuser <<target_port>>/tcp
Let's say the port is 8888, the command becomes:
fuser 8888/tcp
And to kill a process that is running on a port, simply add -k switch.
fuser <<target_port>>/tcp -k
Example (port is 8888):
fuser 8888/tcp -k
That's it! It will close the process listening on the port. I usually do this before running my server application.
I'm adding this answer because for many projects with production deployments, we have scripts that stop these processes so we don't have to.
A clean way to manage your Node Server processes is using the forever
package (from NPM
).
npm install forever -g
forever start -al ./logs/forever.log -ao ./logs/out.log -ae ./logs/err.log server.js
info: Forever processing file: server.js
forever stop server.js
info: Forever stopped process:
uid command script forever pid id logfile uptime
[0] sBSj "/usr/bin/nodejs/node" ~/path/to/your/project/server.js 23084 13176 ~/.forever/forever.log 0:0:0:0.247
This will cleanly shutdown your Server application.
If you want to stop your server with npm stop
or something like this. You can write the code that kill your server process as:
require('child_process').exec(`kill -9 ${pid}`)
Check this link for the detail: https://gist.github.com/dominhhai/aa7f3314ad27e2c50fd5
you can work following command to be specific in localserver kill(here: 8000)
http://localhost:8000/ kill PID(processId):
$:lsof -i tcp:8000
It will give you following groups of TCPs:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 21521 ubuntu 12u IPv6 345668 0t0 TCP *:8000 (LISTEN)
$:kill -9 21521
It will kill processId corresponding to TCP*:8000
My use case: on MacOS, run/rerun multiple node servers on different ports from a script
run: "cd $PATH1 && node server1.js & cd $PATH2 && node server2.js & ..."
stop1: "kill -9 $(lsof -nP -i4TCP:$PORT1 | grep LISTEN | awk '{print $2}')"
stop2, stop3...
rerun: "stop1 & stop2 & ... & stopN ; run
for more info about finding a process by a port: Who is listening on a given TCP port on Mac OS X?
Or alternatively you can do all of these in one line:
kill -9 $(ps aux | grep '\snode\s' | awk '{print $2}')
You can replace node inside '\snode\s' with any other process name.