In Linux, to terminate a process running on a specific port, follow these steps.
Step 1: Locate the Process ID (PID) Running on the Specific Port
You can use the netstat command or the lsof command to find the process ID (PID) of the process bound to a specific port. Here, I'll demonstrate both methods.
Using the netstat Command
-
Open the terminal.
-
Enter the following command, replacing
<port>with the port number you are interested in:bashsudo netstat -nlp | grep :<port>The
-nlpoptions mean:-navoids DNS lookups,-lshows only listening ports, and-pdisplays the process ID and name.
Using the lsof Command
-
Similarly, open the terminal.
-
Enter the following command, replacing
<port>with the port number you are interested in:bashsudo lsof -i :<port>
In the output of these commands, you can identify the corresponding PID. These outputs will show which process is utilizing the specified port.
Step 2: Terminate the Process
Once you have the PID, use the kill command to terminate it. If the normal kill command fails to stop the process, try using kill -9, which forcibly terminates the process.
-
Use the following command, replacing
<PID>with the PID of the process you want to terminate:bashsudo kill <PID> -
If the process does not terminate normally, use:
bashsudo kill -9 <PID>
kill -9 sends signal 9 (SIGKILL) to the process, which is an ungraceful termination that does not allow the process to clean up resources. Therefore, it's best to use the command without -9 first.
Example
Suppose you want to terminate the process running on port 8080:
bashsudo lsof -i :8080
Assume the output shows the PID as 1234. Then run:
bashsudo kill 1234
If the process does not terminate, use:
bashsudo kill -9 1234
These commands provide a quick and effective way to manage port conflicts or unnecessary service issues.