How to kill a process running on a specific port in Windows and Linux
Sometimes, you may encounter a situation where you need to free up a specific port that is being used by a process. Here's a step-by-step guide on how to identify and kill a process running on a particular port.
Steps to kill a process running on a specific port
1. Identify the process ID (PID) associated with the port:
On Windows:
- Open Command Prompt as administrator.
- Run the command:
netstat -ano | findstr :<port_number>
- For example, to find the process running on port 3000, run:
netstat -ano | findstr :3000
- Note down the process ID (the last column) associated with the port.
On macOS/Linux:
- Open the terminal.
- Run the command:
lsof -i :<port_number>
- For example, to find the process running on port 3000, run:
lsof -i :3000
- Note down the process ID (the second column) associated with the port.
2. Kill the process using the identified PID:
On Windows:
- Open Command Prompt as administrator.
- Run the command:
taskkill /F /PID <pid>
- For example, if the process ID is 1234, run:
taskkill /F /PID 1234
- The
/F
flag is used to forcefully terminate the process.
On macOS/Linux:
- Open the terminal.
- Run the command:
kill <pid>
- For example, if the process ID is 1234, run:
kill 1234
- By default, the
kill
command sends a termination signal (SIGTERM
) to the process, allowing it to perform any cleanup operations before shutting down gracefully.
It's important to exercise caution when terminating processes, especially if they are critical or running important tasks. Make sure you are terminating the correct process associated with the desired port.
Example:
Let's say you have a process running on port 3000, and you want to free up that port. To identify the process ID, open Command Prompt (Windows) or terminal (macOS/Linux) and run the command netstat -ano | findstr :3000
(Windows) or lsof -i :3000
(macOS/Linux). Suppose the process ID is 1234. To kill the process, run taskkill /F /PID 1234
(Windows) or kill 1234
(macOS/Linux). This will forcefully terminate the process running on port 3000.
Remember to replace <port_number>
with the actual port number you want to free up, and <pid>
with the process ID you obtained from the previous step.
Happy Coding!