• 1-888-289-2246
  • 24x7x365 Presence

Setting Up a Django Server Using Nginx and Gunicorn


 

 

We’ll setup and configure the Django server on Ubuntu. We are going to configure it with Nginx and Gunicorn for good compatibility and performance.

 

 

• Preparation

 

 

o   Make sure that your system is updated before proceeding with the installation.

§  sudo apt-get update

 

 

• Install and Create Virtualenv

 

 

o   Installing Virtualenv

§  sudo apt-get install python-virtualenv

 

o   Create our Virtualenv environment so we can install Django and other Python packages within it:

§  sudo virtualenv /opt/myenv



• Install Django

 

 

o   Activate the Virtualenv environment so that when we install Python packages they install to our Virtualenv environment

§  source /opt/myenv/bin/activate

 “(myenv)” should have been appended to the beginning of your terminal prompt.

 

o   Install Django

§  pip install django



• Install PostgreSQL

 

 

o   Run the following command to deactivate Virtualenv first:

§  deactivate

 

o   Install dependencies for PostgreSQL to work with Django:

§  sudo apt-get install libpq-dev python-dev

 

o   Install PostgreSQL:

§  sudo apt-get install postgresql postgresql-contrib



• Install Nginx

 

 

o   Install Nginx to use it to serve up our static files for our Django app

§  sudo apt-get install nginx

 

 

• Install Gunicorn

 

 

Gunicorn is a very powerful Python WSGI HTTP Server. 

 

o   Since it is a Python package we need to first activate our virtualenv to install it:

§  source /opt/myenv/bin/activate

 

o   Install Gunicorn

§  pip install gunicorn

 

 

• Configure PostgreSQL

 

 

o   With PostgreSQL we need to create a database, create a user, and grant the user we created access to the database we created.

§  sudo su – postgres

 

o   The terminal prompt should now say “postgres@yourserver”. If this is the case, then run this command to create your database:

§  createdb mydb

 

o   Create your database user with the following command:

§  createuser –P


 You will now be met with a series of 6 prompts. The first one will ask you for the name of the new user. Use whatever name you would like. The next two prompts are for your password and confirmation of password for the new user. For the last 3 prompts just enter “n” and hit “enter”. This just ensures your new users only have access to what you give them access and to nothing else.

 

o   Now activate the PostgreSQL command line interface like so:

§  psql

 

o   Grant this new user access to your new database with this command:

§  GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;

 

o   Switch back to your user from the postgre user:

§  exit



• Create a Django Project

 

 

o   Change directories into the directory of your virtualenv

§  cd /opt/myenv

 

o   Activate your virtualenv

§  source /opt/myenv/bin/activate

 

o   Run the following command to start a new Django project:

§  django-admin.py startproject myproject

 In order for Django to be able to talk to our database we need to install a backend for PostgreSQL.

 

o   Make sure your virtualenv is active and run the following command in order to do this:

§  pip install psycopg2

 

o   Change directories into the new “myproject” directory and then into its subdirectory which is also called “myproject” like this:

§  cd /opt/myenv/myproject/myproject

 

o   Edit the settings.py file:

§  nano settings.py


Sample Configuration


DATABASES = {
    ‘default’: {
        ‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’, # Add ‘postgresql_psycopg2’, ‘mysql’,  ‘sqlite3’ or ‘oracle’.
        ‘NAME’: ‘mydb’, # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        ‘USER’: ‘myuser’,
        ‘PASSWORD’: ‘password’,
        ‘HOST’: ‘localhost’, # Empty for localhost through domain sockets or ‘127.0.0.1’ for localhost through TCP.
        ‘PORT’: ”, # Set to empty string for default.
    }
}

 


o   Move up one directory so you’re in your main Django project directory (opt/myenv/myproject).

§  cd /opt/myenv/myproject

 

o   Activate your virtualenv if you haven’t already with the following command:

§  source /opt/myenv/bin/activate

 

o   Run the following command so that Django can add its initial configuration and other tables to your database:

§  python manage.py syncdb

 

You should see some output describing what tables were installed, followed by a prompt asking if you want to create a superuser. This is optional and depends on if you will be using Django’s auth system or the Django admin.

 

 

• Configure Gunicorn

 

 

o   First let’ s just go over running Gunicorn with default settings.

§  gunicorn_django –bind 0.0.0.0:8000


You may provide the domain name or IP of your VPS instead of 0.0.0.0 to bind the server to a specific IP or domain. It’s a good practice to bind it to your VPS address. Now go to your web browser and visit VPS_IP:8000 and see what you get. You should get the Django welcome screen.

 

o   If you have a large-scale application on a large VPS then increase the worker processes:

§  gunicorn_django –workers=2 –0.0.0.0:8000

 

o   If you want to set more options for Gunicorn, then set up a config file that you can call when running Gunicorn. Navigate to the directory of your virtualenv.

§  cd /opt/myenv

 

o   Open your config file

§  sudo nano gunicorn_config.py

 

o   Add the following contents to the file:


## Add these lines in your exising file
command = ‘/opt/myenv/bin/gunicorn’
pythonpath = ‘/opt/myenv/myproject’
bind = ‘127.0.0.1:8000’
workers = 2
user = nobody


Save and exit the file.



o   To run the server, Enter the following command:

§  sudo /opt/myenv/bin/gunicorn -c /opt/myenv/gunicorn_config.py myproject.wsgi


The ‘-c’ flag is used to define the config file path.

 

 

• Autostart gunicorn

 

 

o   Install the Supervisor package:

§  sudo apt-get install supervisor

 

o   Create a script to inititate gunicorn:

§  sudo nano /usr/local/bin/run_gunicorn.sh


Sample Config File


#!/bin/bash
echo `date`
sudo /opt/myenv/bin/gunicorn -c /opt/myenv/gunicorn_config.py myproject.wsgi


o   Add the program to startup list:

§  nano /etc/supervisor/conf.d/myproject1_gunicorn.conf

 

Sample File


[program:myproject1_gunicorn]
command=/usr/local/bin/run_gunicorn.sh
autostart=true
autorestart=true
stderr_logfile=/var/log/myproject1_gunicorn.err.log
stdout_logfile=/var/log/myproject1_gunicorn.out.log



o   Make the supervisor reread the setting and add your task:

§  sudo supervisorctl reread

§  sudo supervisorctl update



• Configure Nginx

 

 

o   Start the Nginx server:

§  sudo service nginx start

 

o   Since we are setting NGINX to handle static files only we need to set our static files location first. Open your settings.py file for your Django project and edit the STATIC_ROOT line:

§  STATIC_ROOT = “/opt/myenv/static/”

 

o   Configure NGINX to handle those files. Open up a new NGINX config file with the following command:

§  sudo nano /etc/nginx/sites-available/myproject


Sample File


server {
    server_name djangoserver.devops;

    access_log off;

    location /static/ {
        alias /opt/myenv/static/;
    }
    
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P ‘CP=”ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV”‘;
    }
}


o   Now we need to set up a symbolic link in the /etc/nginx/sites directory that points to this configuration file. That is how NGINX knows this site is active. Change directories to /etc/nginx/sites-available like this:

§  cd /etc/nginx/sites-available

§  sudo ln -s ../sites-available/myproject

 

o   Remove the default nginx server block:

§  sudo rm default

 

o   Now restart nginx

§  sudo service nginx restart

 

o   Navigate to the IP address of your server and you will see the default Django page there:


Django welcome screen


 

We have configured a Django server with Nginx and Gunicorn successfully.


]]>