Django is a powerful web development framework written in Python that allows developers to create complex and database-driven Python applications. In this tutorial, we will guide you through the process of installing Django on Debian 11, setting up a Python virtual environment, configuring the PostgreSQL database, and using Nginx as a reverse proxy for your Django application.
Prerequisites
Before we begin, make sure you have the following prerequisites:
- A server running Debian 11
- A valid domain name pointed to your server’s IP address
- Root access to the server
Getting Started
First, let’s update the system packages to the latest version by running the following command:
apt-get update -y
Next, install the necessary packages for Python and Nginx:
apt-get install python3-pip python3-dev libpq-dev curl nginx -y
Install PostgreSQL Database Server
We will be using PostgreSQL as the database backend for our Django application. Let’s install PostgreSQL by running the following command:
apt-get install postgresql postgresql-contrib -y
Once PostgreSQL is installed, we need to create a database and a user for Django. Switch to the PostgreSQL shell by running:
su - postgres
psql
Within the PostgreSQL shell, execute the following commands to create a database and user for Django:
CREATE DATABASE django; CREATE USER django WITH PASSWORD 'password';
Next, grant the required roles to the Django user:
ALTER ROLE django SET client_encoding TO 'utf8';
ALTER ROLE django SET default_transaction_isolation TO 'read committed';
ALTER ROLE django SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE django TO django;
Exit the PostgreSQL shell by running:
q exit
Create a Python Virtual Environment
Now, let’s create a Python virtual environment for our Django project. This step will ensure that the dependencies for our project are isolated from the system Python installation.
First, upgrade the PIP package to the latest version:
pip3 install --upgrade pip
Verify the PIP version:
pip --version
Install the virtual environment package:
pip3 install virtualenv
Create a directory for your Django project and navigate to it:
mkdir ~/djangoapp cd ~/djangoapp
Create the virtual environment:
virtualenv djangoenv
Activate the virtual environment:
source djangoenv/bin/activate
Install Django, Gunicorn, and other required packages:
pip install django gunicorn psycopg2-binary
Install and Configure Django
Now that our virtual environment is set up, let’s install and configure Django.
Create a new Django project:
django-admin.py startproject djangoapp ~/djangoapp
Edit the settings.py
file and update the following lines with your domain name:
ALLOWED_HOSTS = ['django.example.com', 'localhost']
Uncomment the default database backend and add the PostgreSQL database settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
Add the following lines at the end of the file:
STATIC_URL = '/static/' import os STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
Save and close the file.
Migrate the initial database schema to the PostgreSQL database:
./manage.py makemigrations ./manage.py migrate
Create a superuser account for Django:
./manage.py createsuperuser
Follow the prompts to set your admin username and password.
Gather all the static content into the appropriate directory:
./manage.py collectstatic
Run the Django Development Server
Now that Django is installed and configured, let’s start the development server to test our application.
./manage.py runserver 0.0.0.0:8000
If everything is set up correctly, you should see the following output:
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 27, 2021 - 10:02:05 Django version 3.2.6, using settings 'djangoapp.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C.
Open your web browser and access your Django project using the URL http://django.example.com:8000/admin/
. You will be redirected to the Django login page. Enter your admin username and password to access the Django dashboard.
To stop the development server, press CTRL + C
in the terminal.
Verify Django with Gunicorn
Next, let’s test whether Gunicorn can serve our Django application.
Start Gunicorn with the following command:
gunicorn --bind 0.0.0.0:8000 djangoapp.wsgi
If everything is working correctly, you should see output similar to the following:
[2021-08-27 10:04:22 +0000] [47383] [INFO] Starting gunicorn 20.1.0
[2021-08-27 10:04:22 +0000] [47383] [INFO] Listening at: http://0.0.0.0:8000 (47383)
[2021-08-27 10:04:22 +0000] [47383] [INFO] Using worker: sync
[2021-08-27 10:04:22 +0000] [47384] [INFO] Booting worker with pid: 47384
To stop Gunicorn, press CTRL + C
in the terminal.
Deactivate the Python virtual environment:
deactivate
Create a Systemd Service File for Gunicorn
To ensure that our Django application starts and stops automatically with the server, we will create a systemd service file for Gunicorn.
Create a socket file for Gunicorn:
nano /etc/systemd/system/gunicorn.socket
Add the following lines to the file:
[Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target
Save and close the file.
Create a service file for Gunicorn:
nano /etc/systemd/system/gunicorn.service
Add the following lines to the file, updating the path to match your Django project:
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/root/djangoapp
ExecStart=/root/djangoapp/djangoenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock djangoapp.wsgi:application
[Install]
WantedBy=multi-user.target
Save and close the file.
Set the proper permissions for the Django project directory:
chown -R www-data:root ~/djangoapp
Reload the systemd daemon to apply the changes:
systemctl daemon-reload
Start the Gunicorn service and enable it to start at system reboot:
systemctl start gunicorn.socket systemctl enable gunicorn.socket
Check the status of the Gunicorn service:
systemctl status gunicorn.socket
If everything is configured correctly, you should see output similar to the following:
● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; disabled; vendor preset: enabled) Active: active (listening) since Fri 2021-08-27 10:05:46 UTC; 6s ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket
Configure Nginx as a Reverse Proxy For Django
Finally, we will configure Nginx as a reverse proxy to serve our Django application.
Create an Nginx configuration file:
nano /etc/nginx/conf.d/django.conf
Add the following lines to the file, replacing django.example.com
with your domain name:
server { listen 80; server_name django.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/djangoapp; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } }
Save and close the file.
Verify the Nginx configuration for any errors:
nginx -t
If the configuration is valid, you should see the following output:
nginx: configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Finally, restart the Nginx service to apply the changes:
systemctl restart nginx
To check the status of Nginx, run:
systemctl status nginx
If everything is configured correctly, you should see output similar to the following:
● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Active: active (running) since Fri 2021-08-27 10:06:59 UTC; 6s ago Docs: man:nginx(8) Process: 47494 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Process: 47495 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS) Main PID: 47496 (nginx) Tasks: 2 (limit: 2341) Memory: 2.5M CPU: 49ms CGroup: /system.slice/nginx.service ├─47496 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; └─47497 nginx: worker process
Conclusion
Congratulations! You have successfully installed Django on Debian 11 and configured it to run with Gunicorn and Nginx as a reverse proxy. You can now start developing and deploying your Python web application using the Django framework. If you encounter any issues during the installation process, please refer to the official Django documentation or seek assistance from the Django community.
Thank you for choosing Shape.host services, the leading provider of Linux SSD VPS hosting. We hope this tutorial has been helpful in getting your Django application up and running. If you have any further questions or need assistance with your hosting needs, feel free to reach out to our support team. Happy coding!