1

I develop on serveral projects at once.

If I run the runserver twice, I get this error:

System check identified no issues (0 silenced).
September 10, 2021 - 10:44:26
Django version 3.1.4, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Error: That port is already in use.

I know that I can supply a different port manually, but a more automatic approach would be nice.

How could I solve this clash without manually giving each project a port by hand?

I have more than 50 systems on my laptop, and I don't want to give them each a port number by hand.

guettli
  • 25,042
  • 81
  • 346
  • 663
  • 1
    create separate bash scripts for your projects which run them at different ports. – Pranava Mohan Sep 10 '21 at 10:57
  • @PranavaMohan I have more than 50 systems on my laptop, and I don't want to give them each a port number by hand. – guettli Sep 11 '21 at 09:11
  • 1
    but why are you running more than 50 projects at once? Are you doing any sci-fi thing? The problem will only arise if a project is already running in that port. Most probably, you will be working with 1-5 projects at once, you can at least create bash scripts for them. – Pranava Mohan Sep 11 '21 at 14:01
  • @PranavaMohan of course I don't run all at once. In most cases I run 3 runserver at once. Nevertheless the port-clash problem exists. – guettli Sep 12 '21 at 16:06
  • So you are saying that, you ran your projects at different ports, but still the problem exists. If you are on windows, you can open your powershell window and type this command - `netstat -aon | findstr '[port_number]'` where `[port number]` is the port that you are using to run your projects. If you are on mac, run this- `netstat -vanp tcp | grep [port_number]`. These commands will list out the programs using that particular port. Find the program which is using the port and kill it :) – Pranava Mohan Sep 13 '21 at 00:40
  • do you want to use 8000 for all your application? or port can be dynamic? – Sabil Sep 16 '21 at 05:12
  • @Sabil my prefered solution would be something like `settings.DEFAULT_RUNSERVER_PORT`. But other solutions are welcome. – guettli Sep 16 '21 at 07:00
  • What happen if your default server port is already being used? – Sabil Sep 16 '21 at 07:02
  • @Sabil if I can configure it, then the ports won't clash. Except the config is broken, then I need to fix the config by hand. That's ok. – guettli Sep 16 '21 at 07:02
  • great. could you please share your approach so far? or any solution that you tried? – Sabil Sep 16 '21 at 07:05
  • @Sabil I created an answer to my question, and if I have working code, I will create a hyperlink from here to the code. But maybe this will never happen. – guettli Sep 16 '21 at 08:25
  • Docker may not be an unreasonable way to handle this. Running your apps on the docker network avoids the port resource problem because each container gets its own IP. – sytech Sep 16 '21 at 09:05
  • @sytech I very happy with python and virtualenv. I don't need docker to give my network interface several 127.x.x.x IPs. – guettli Sep 16 '21 at 13:56
  • 1
    @guettli, have a look at https://stackoverflow.com/a/38319452/6143954. _Currently (as of 2.0.3) you can just add: `from django.core.management.commands.runserver import Command as runserver; runserver.default_port = "8080 to your manage.py`._ – NKSM Sep 16 '21 at 14:12
  • @guettli You can give a try with my approach and let me know if it resolves your issue or not. :) – Sabil Sep 19 '21 at 13:00

5 Answers5

3

You can create your own manage command runsever_foo.

Then you can fetch the default value for the port from settings.py or from os.environ.

guettli
  • 25,042
  • 81
  • 346
  • 663
3

You can implement something like following.

  1. Add RUN_SERVER_PORT in settings.py
RUN_SERVER_PORT = 8080
  1. Implement following code in manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from django.core.management.commands.runserver import Command as runserver
from django.conf import settings


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accountant.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    runserver.default_port = settings.RUN_SERVER_PORT
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

Proof of Work:

python manage.py runserver

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
September 19, 2021 - 12:47:59
Django version 3.2.6, using settings 'accountant.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.

You can use any available port in RUN_SERVER_PORT

Sabil
  • 3,750
  • 1
  • 5
  • 16
1

Reference to this post: https://stackoverflow.com/a/38319452/16936785

I would recommend to amend the server port under manage.py into the following for a random port selection:

import random
from django.core.management.commands.runserver import Command
port_number = random.randint(8000, 8888)
Command.default_port = str(port_number)
Ahmed Ablak
  • 718
  • 3
  • 14
1

put this in your .bashrc .zshrc or .bash_profile depends on your environment.

#!/usr/bin/env bash

function runserver()
{
    local PORTNUM=8000
    for (( ; ; )); do
        nc -z 127.0.0.1 $PORTNUM
        [ $? -ne 0 ] && break
        PORTNUM=$(( $RANDOM % 1000 + 8000 ))
    done
    python manage.py runserver $PORTNUM $@
}

Then just run runserver and it should bring up a test server with a port in the range of [8000, 9000)

This function uses netcat to test if the port is available, you might need to install netcat.

rabbit.aaron
  • 2,369
  • 16
  • 25
0

To run Django on different port

python manage.py runserver <your IP>:<port> : python manage.py runserver 0.0.0.0:5000

Or python manage.py runserver <port> : python manage.py runserver 5000

For automation Create a bash script like django_5000 and django_7000 where you execute differents command according to your desired port.

Rvector
  • 2,312
  • 1
  • 8
  • 17