Django change default runserver port
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:
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:
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
:
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:
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:
Then, start your Docker container using this command:
In here, 8001
is the port on your host machine that is cross-linked with port 8000
of the container.
Was this article helpful?