FUNDAMENTAL

How to kill server running at a port in macOS

Problem?

While working with node js project (npm or yarn) in the terminal, sometimes we face a strange problem. Sometimes even if we close the server in terminal, still it is runing under the hood. When we restart the server again (using npm start or yarn start), it ask for assigning new port.

But we don't want to do that. Under the hood server is occupying that port and we want to use that port.

If you are using mac os, here is quick step to kill the server which is runing under the hood.

Steps to solve this problem

  1. Find the Process ID (PID)

First of all you will need to find the process ID on which that server is running on that specific port.

For example, if server was running at port 8000, you can find the PID using this below command:

sudo lsof -ti :8000

Result:

89711

here, irdmi is basically represents port 8000.

  1. Kill Process ID (PID)

Use this command to kill the process.

kill -9 <PID>

e.g.:

kill -9 89711

That's all.

In single line, you can write command as below

kill -9 $(lsof -ti:<PortNumber>)

e.g.:

kill -9 $(lsof -ti:8000)