Explain Codes LogoExplain Codes Logo

Django change default runserver port

python
django
runserver
configuration
Nikita BarsukovbyNikita Barsukov·Jan 19, 2025
TLDR

To alter Django's server port, append your desired port number to the runserver command. For instance, you can switch to port 8001 by executing:

python manage.py runserver 8001

This command operates the Django development server on port 8001, replacing the default port (8000). Read on for more techniques, including methods to adjust the default port in a more systematic manner.

Advanced configuration

Using a bash script

Utilize a bash script to simplify your server launch with a customized port. Here is how it can be done:

#!/bin/bash # If Bash were a music style, it obviously would be rock'n'roll! python manage.py runserver 8005

After creating the script, make it executable and position it in the same directory as manage.py. Subsequently, running ./runserver.sh will get your server up and running.

Adjusting port via config.ini

Dodge the hassle of hardcoding the port by employing config.ini:

# within manage.py import configparser config = configparser.ConfigParser() config.read('config.ini') port = config['server']['port'] # Just like a self-stirring mug for lazy programmers. execute_from_command_line(sys.argv + [port])

With this setup, you just run python manage.py runserver as usual, and the server will adeptly pick the port from config.ini.

Creating custom management commands

Another useful way of changing the default port value is via custom management commands:

# In yourapp/management/commands/runserver.py from django.core.management.commands.runserver import Command as RunserverCommand class Command(RunserverCommand): # This one goes to eleven! def handle(self, *args, **options): options['port'] = '8005' # Replace with dynamic retrieval logic super().handle(*args, **options)

You can set a new port in a separate config.ini, then create a subclass of RunserverCommand where options['port'] is assigned the value corresponding to the new port.

Configuring environment variables

Before using manage.py, don't forget to set up an environment variable named DJANGO_SETTINGS_MODULE and run django.setup(). This procedure guarantees that all required settings are loaded, which might include any adjustments made to the default port.

Using Dockers for port configuration

If your project uses Dockers, you can simply map your custom port to Django's default on Docker:

EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

Then, start your Docker container using this command:

docker run -p 8001:8000 django-app

In here, 8001 is the port on your host machine that is cross-linked with port 8000 of the container.