Kill process running under certain port

So you have started your django or Ruby on Rails development server. Then you make some code changes that require the dev server reboot. Usually the server automatically watches your code files and reboot by itself, but sometimes, It doesn't. You have to stop or restart the server process manually.

Usually the devp server daemon will tell you "Quit the server with CONTROL-C". But we all know this doesn't work.

#python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).  
May 10, 2018 - 14:20:33  
Django version 2.0, using settings 'sitemonkey.settings'  
Starting development server at http://127.0.0.1:8000/  
Quit the server with CONTROL-C.  
Error: That port is already in use.  

The long solution is to look for process ID or PID of the server listening on whatever port it's running such as 8000. You can do this by running netstat or lsof or ss. Get the PID and then run the kill command.

But you can achieve the same using a single one-liner;

sudo kill $(sudo lsof -t -i:8000)  
#or 
sudo fuser -k -n tcp 8000  

That's it. Now you can run your dev server again and it won't complain that "port is already in use".

David Okwii

David Okwii is a Systems Engineer who currently works with Africa's Talking, a pan-African company serving millions of API queries for SMS/USSD/Voice, Airtime and Mobile Payments across 6 countries.

Kampala Uganda http://www.davidokwii.com

Subscribe to David Okwii dev blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!