I used to have trouble with processes blocking ports while developing. I would type up a number of commands trying to find the pid of the process that’s blocking the port and kill that process. It was rather frustrating. Eventually I took the commands and wrote a script that kills processes based on the port that it’s using.
https://gist.github.com/tmanOC/76e643cb742338d94120e7d8cceb312a
You run it with ./kill_script_by_port.sh with the port number as an argument.
The first line uses the lsof command to get the processes using that port. For example lsof -i:52639 outputs the following on my machine
https://gist.github.com/tmanOC/bedf1d99886c00147ca29f9a392b7996
This output gets piped into awk which gets the 2nd word of every line. grep removes the PID word. Finally sort -u removes any duplicate PIDs.
The rest of the code reads the PIDs into an array and loops through them killing all the processes that use the port.
If there’s a particular process you know you don’t want to kill, you can put the command for the process as an argument to grep -v -e before the awk in the pipeline. That process will be removed from the lsof output.








