Snippets Nginx / Serving Django

Serving Django

By Marcelo Fernandes Jul 09, 2017

Serving Django via Nginx and uWSGI

Updated tutorial: How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04

Step 1: Getting the dependencies.

# Basic Set Up
sudo apt-get update
sudo apt-get install python3-pip

# Virtual environment tools
sudo pip3 install virtualenv virtualenvwrapper

Step 2: Install the virtual Env

echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.6" >> ~/.bashrc

echo "export WORKON_HOME=~/Env" >> ~/.bashrc

echo "source /usr/local/bin/" >> ~/.bashrc

# Source the shell initialization script in order to use
# this functionality in the current session
source ~/.bashrc

Step 3: Make the virtual Env via virtualenvwrapper

# Create it with the name of your project.
mkvirtualenv projectenv
# Remember to install your dependencies.
pip install django

whenever you have to work on your env use the command:

# Activate
workon projectenv
# Deactivate

Step 4: Installing uWSGI

# Packages that the software relies on
sudo apt-get install python-dev
# Install uwsgi
sudo pip3 install uwsgi

You might test it quickly

# Set the project to work on the virtual env and run the
uwsgi --http :8080 --home /home/user/Env/projectenv --chdir django/manage.pyFolder -w project_root.wsgi

Step 5: Creating configuration Files

# Since its an global process
sudo mkdir -p /etc/uwsgi/sites
cd /etc/uwsgi/sites

For each django project (if you are serving more than one)
create a configuration file. sudo nano projectname.ini Inside this folder, the config should be: [uwsgi] project = django/root/folder base = /home/user chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 5 socket = %(base)/%(project)/%(project).sock chmod-socket = 664 vacuum = true
Step 5: Create an Upstart Script for uWSGI

sudo nano /etc/init/uwsgi.conf

set your file to:

description "uWSGI application server in Emperor mode"

start on runlevel [2345]
stop on runlevel [!2345]

Save and Close
Step 6: Configure Nginx

# Install it
sudo apt-get install nginx

# configure a server block configuration
sudo nano /etc/nginx/sites-available/firstsite

Insert in the file:

server {
    listen 80;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/user/firstsite;

    location / {
        include         uwsgi_params;
        uwsgi_pass      unix:/home/user/firstsite/firstsite.sock;

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



link 1