Serving Your Django Application With Nginx Using uWSGI

Posted By :Mahendra Singh |26th February 2021

Introduction:

Django is a ground-breaking web structure that can assist you with getting your Python application or site going. Django incorporates an improved on advancement worker for testing your code locally, yet for anything even somewhat creation-related, a safer and ground-breaking web worker is required.

In this guide, we will show how to introduce and design a few segments on Linux to help and serve Django applications. We will create the uWSGI application worker to interface with our applications. We will at that point set up Nginx to invert intermediary to uWSGI, giving us admittance to its security and execution highlights to serve our applications.

 

Prerequisites:

To finish this guide, you should have complete the below points on a new Ubuntu/Linux.

 

 *  A non-root user with Sudo advantages.

 * Install Python with Pip.

 * Install & Create a python virtual environment for the backend(Django).
 * Install Nginx web server.

 * Install Database server & configure it for authentication with username & password.

 

Download & Setup Your Django Project :

 

   * Create & Activate the environment  & go to the backend source code directory.

   * Download your project using GIT & Install the requirements using PIP.

      

sudo python -m venv $env_name
source venv_name/bin/activate   //activate the environment    
git clone  https://github........git 
pip install -r requirement.txt  //install django dependencies  

   

   * Configured the database login credentials in Django source code & Do migrate the database for Django.

    python manage.py makemigrations
    python manage.py migrate

  

   * Start & Test the Django server

    python manage.py runserver 0.0.0.0:8000

 This Python command will start the development server on 8000 port You can test your server using your server's domain name or IP address followed by 8000 in your browser:

http://server_domain_or_IP:8000

After testing  To stop the development server type Ctrl+c in the termianl.

  

   * Deactivate the Virtual Environment

($env_name)$deactivate

We can now move forward and configure the application server.

 

Setting Up The uWSGI Application Server:

    Now we have the Django application installed & ready to go, So now we're going to configure uWSGI. uWSGI is a software service that could communicate with application programs over an interface known as WSGI.

 

     * Installing uWSGI

        - For Django with Python 3      

sudo apt-get install python3-dev
sudo -H pip3 install uwsgi

We can quickly check this utility server by passing it the facts for one in all our sites. Run the application using uWSGI .

      uwsgi --http :8000 --home $venvpath --chdir $django-source-code-path -w $django_app_name.wsgi

Here we've told uWSGI our environment & source code location using --home and --chdir arg...

Running uWSGI from the command line is beneficial for testing, however isn’t mainly useful for a real deployment. here we will create a configuration .ini file  that will run uWSGI in “Emperor mode”, which allows a master process to manage applications automatically.

    sudo mkdir -p /etc/uwsgi/sites
    sudo mkdir -p /var/log/uwsgi-logs
    sudo nano /etc/uwsgi/sites/flash.ini


The configuration will look like this:

[uwsgi]
project = project_name
uid = $user
base = backend source path

chdir = %(base)/%(project)
home = %(base)/Env/%(project)
module = %(project).wsgi:application
master = true
processes = 5
socket = /run/uwsgi//%(project).sock
logto = /var/log/uwsgi-logs/uwsgi.log
chown-socket = %(uid):www-data
chmod-socket = 660
vacuum = true

Here, our project’s uWSGI configuration is complete.

 

Create a systemd Unit File for uWSGI :

Here. we will create a systemd unit file to manage the uWSGI and automatically start uWSGI at startup. This will make the full process automatic.

sudo nano /etc/systemd/system/uwsgi.service

The configuration will look like this:


[Unit]
Description=uWSGI Emperor service
[Service]
ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown sammy:www-data /run/uwsgi'
ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites
Restart=always
KillSignal=SIGQUIT
Type=notify
NotifyAccess=all
[Install]
WantedBy=multi-user.target

 

So now we have configured the Uwsgi & systemd file but we can't able to start the service successfully because the www-data user relies on Nginx web server.

    - Install and Configure Nginx as a Reverse Proxy forBackend app.  we will create basic configurations including the uwsgi parameters found in the /etc/nginx/uwsgi_params and pass the traffic to the uwsgi server's socket.

sudo apt-get install nginx
sudo nano /etc/nginx/sites-available/djangoapp

 

 * The configuration of these items will look like this:

server {
    listen 80;
    server_name example.com www.example.com;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/sammy/secondsite;
    }
    location / {
        include         uwsgi_params;
        uwsgi_pass      unix:/run/uwsgi/secondsite.sock;
    }
}

 

    sudo ln -s /etc/nginx/sites-available/djangoapp /etc/nginx/sites-enabled

 * Check the configuration:

sudo nginx -t

Now, Restart the Nginx & uWSGI services.

   sudo systemctl restart nginx
   sudo systemctl start uwsgi

  * Allow the UFW rules for Nginx

sudo ufw allow 'Nginx Full' //allow firewall

  * Enable both services to start automatically at boot:

    sudo systemctl enable nginx  
    sudo systemctl enable uwsgi

* If you made any changes in your Django application, you should restart the uWSGI service & if you made any changes in systemd file, you have to reload the daemon.

sudo systemctl daemon-reload
sudo systemctl restart uwsgi

 * After any Nginx changes::

sudo nginx -t && sudo systemctl restart nginx

 

So, now we have set up our Django application using a virtual environment and configured uWSGI, and configured the Nginx web server as reverse proxy you can check your application using your server IP/Domain name in the browser.

http://server'sIP/Domain

 

Conclusion :

In the production environment using uWSGI is the best way to serve your Django application. here we've deployed our Django application using uWSGI and Nginx reverse proxy which will serve our project at client's request.

 


About Author

Mahendra Singh

Mahendra is a DevOps Engineer with hands-on experience supporting automating and optimizing deployments in AWS, configuration management, and DevOps processes with Ansible, Github, Docker, Python, Nginx, and Linux.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us