How to 'clear' the port when restarting django runserver

Often, when restarting Django runserver, if I use the same port number, I get a 'port is already in use' message. Subsequently, I need to increment the port number each time to avoid this.

It's not the case on all servers, however, so I'm wondering how I might achieve this on the current system that I'm working on?

BTW, the platform is Ubuntu 8.10


Solution 1:

I found this information (originally from Kristinn Örn Sigurðsson) to solve my problem:

To kill it with -9 you will have to list all running manage.py processes, for instance:

ps aux | grep -i manage

You'll get an output similar to this if you've started on many ports:

14770     8264  0.0  1.9 546948 40904 ?        S    Sep19   0:00 /usr/local/bin/python manage.py runserver 0.0.0.0:8006
14770    15215  0.0  2.7 536708 56420 ?        S    Sep13   0:00 /usr/local/bin/python manage.py runserver 0.0.0.0:8001
14770    30144  0.0  2.1 612488 44912 ?        S    Sep18   0:00 /usr/local/bin/python manage.py runserver 0.0.0.0:8000
14770    30282  0.0  1.9 678024 40104 ?        S    Sep18   0:00 /usr/local/bin/python manage.py runserver 0.0.0.0:8002
14770    30592  0.0  2.1 678024 45008 ?        S    Sep18   0:00 /usr/local/bin/python manage.py runserver 0.0.0.0:8003
14770    30743  0.0  2.1 678024 45044 ?        S    Sep18   0:00 /usr/local/bin/python manage.py runserver 0.0.0.0:8004

Then you'll have to select the pid (which is the second number on the left) for the right manage.py process (python manage.py runserver... etc) and do:

kill -9 pid

For the above example, if you wanted to free up port 8000, you'd do:

kill -9 30144

Solution 2:

You're getting that message because the server is already running (possibly in the background). Make sure to kill the process (bring it to the foreground and press ctrl-c) to stop the process.

Solution 3:

If the ps aux command (as per Meilo's answer) doesn't list the process that you wanted to kill but shows the port active in netstat -np | grep 8004 network activity, try this command (worked on Ubuntu).

sudo fuser -k 8004/tcp

where as, 8004 is the port number that you want to close. This should kill all the processes associated with port 8004.

Solution 4:

No, he's not an idiot guys. Same thing happens to me. Apparently it's a bug with the python UUID process with continues running long after the django server is shutdown which ties the port up.

Solution 5:

fuser -k 8000/tcp

Run in terminal it works in ubutu. 8000 is the port.