How to Install & Configure Django with Postgres, Nginx, and Gunicorn
Edit Article

  • 1 Editor

Django is not a new subject to many of us. But, several concepts must have gone astray from our minds without a proper update. Don't worry, we will help to rewind and get your selves updated.


First let us start with some basics

What is Django?

Django is a free and open source web server gateway interface, written in Python. Django follows the model view controller architectural pattern. Django is an interface in web servers and Python to promote web application portability.


Hope you have now refreshed your memory


Now , we will discuss about Install and Configure Django with Postgres, Nginx, and Gunicorn. Many of you now will have several doubts. Let me guess a few:

  1. What is Django terminology?
  2. How to install Django and how to configure it in our system?
  3. How to connect with Django server for client server or on local machine?
  4. How contents are exported in Django format?

Don’t worry; here I have the answers to all your doubts.

How To Install and Configure Django with Postgres, Nginx, and Gunicorn :

Now make sure that your system and repositories are up to date and need to install and create virtualenv. Run the following commands:-

# sudo apt-get update
# sudo apt-get upgrade
# sudo apt-get install python-virtualenv
# sudo virtualenv /opt/virtualenv

You have created the directory, the home for virtualenv. Before we carry on with Python packages installation, you need to activate our virtualenv.

# source /opt/virtualenv/bin/activate

Now you will see that (virtualenv) has been appended to the start of the terminal prompt. This will aid you to understand when your virtualenv is active. Suppose, in case we have many virtualenv’s on the VPS, it will help you to know which is active. Now to install Django, we will use pip:

Install Django

# pip install django

We have now installed Django. The next step is the database. Most Django users prefer to use PostgreSQL as their database server. It is much tough than MySQL and the Django. ORM works much better with PostgreSQL than MySQL, MSSQL, or others. We do not require Virtualenv active for PostgreSQL installation, so we can deactivate it:

# deactivate

Install PostgreSQL

Then you need to install dependencies for PostgreSQL. install PostgreSQL database service:

# sudo apt-get install libpq-dev python-dev
# sudo apt-get install postgresql postgresql-contrib

PostgreSQL is now installed on your VPS. Now install is nginx. We will use nginx as web server because it fast and light server and compatible with Python. To install it, we may execute:

Install NGINX

# sudo apt-get install nginx

Gunicorn is a powerful Python web server gateway interface HTTP Server. It is a Python package you need to first activate your virtualenv to install it. Run the following command:

Install Gunicorn

# source /opt/myenv/bin/activate
# pip install gunicorn

Now Gunicorn installed in your system, you need start services configuration process with PostgreSQL. Now create a database, a user, and grant the user access to the database you created with PostgreSQL. Run the following command:

Configure PostgreSQL

# sudo su – postgres

Run the following command to create your database and named newdb, create database user:

# created newdb
# createuser –P

Now we will get a chain of 6 prompts in the process. The first one will ask you the name of new user. The next two are for your password and confirmation of password of new user. For the last 3 prompts enter “n” and press enter key. This will ensure your new users only have access to what you want it access to and nothing else. Now start PostgreSQL console and set access for the new user:

# psql
# GRANT ALL PRIVILEGES ON DATABASE newdb TO newuser;

Now you have database with an accessible user. For creating new Django project, change to virtualenv directory and activate it. Now you can create a new project:

Create a Django Project

# cd /opt/myenv
# source /opt/myenv/bin/activate
# django-admin.py startproject newproject

You will be able to see a new directory called “newproject” inside virtualenv directory. Here your new Django project files exist. To let your projects talk to our database, you need to install extra packages with using pip, while virtualenv still active.

# pip install psycopg2

Then change your project’s directory and edit settings.py file using editor. The database settings in the file should be as followed:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2',
 'mysql', 'sqlite3' or 'oracle'.'NAME': 'newdb', # Or path to database file if using sqlite3.
# These settings are not used with sqlite3:
'USER': 'newuser',
'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.
}

Now make sure virtualenv is activating. Run the following command to add django's primary configuration and other tables to your database:

# cd /opt/virtualenv/newproject
# source /opt/myenv/bin/activate
# python manage.py syncdb

Configure Gunicorn

Gunicorn configuration is specific. First you will run Gunicorn with default settings. follow the command to run default Gunicorn:

# gunicorn_django --bind **your-fully-qualified-domain-name.com**:8001

You can control the processes from the following command line. If you want to start 5 worker processes, run the following command:

# gunicorn_django –workers=5 --bind **your-fully-qualified-domain-name.com**:8001

If you want to run Gunicorn and user, then run the following command:

# gunicorn_django --workers=5 --user=nobody --bind **your-fully-qualified-domain-name.com**:8001

Hope you have understood till now.


Now you may be facing different input parameters. It is better to create configuration file and use it when starting Gunicorn. Create your configuration file in virtualenv directory for instance /opt/virtualenv/gunicorn_cfg.py, and run the following:

command = '/opt/myenv/bin/gunicorn'
pythonpath = '/opt/myenv/myproject'
bind = '127.0.0.1:8001'
workers = 5
user = 'nobody'
Now, if you want to run the server, run the following command:
# /opt/myenv/bin/gunicorn -c /opt/myenv/gunicorn_config.py 
myproject.wsgi

Here “-c” refers gunicorn that you have a config file you want to use. Also pass a Python dotted notation reference to your web server gateway interface file. So the Gunicorn knows where your web server gateway interface file is. The last step you need to take is to configure nginx.

Configure NGINX

Open your settings.py file of Django project and edit the STATIC_ROOT command like this:

STATIC_ROOT = "/opt/virtualenv/static/"

Well hope you guys are now clear with the concepts


Now you need to set up your static files location, you need to configure NGINX to work the static files and to connect to Gunicorn. You should create a file named /etc/nginx/sites-enabled/newproject and follow the following command:

server {
    server_name **your-domain-name.com**;

    access_log off;

    location /static/ {
        alias /opt/virtualenv/static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        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"';
    }
}

For apply settings, you need to restart Nginx and you are good to go:

# sudo service nginx restart

You can repeat the procedure for creating new application. This way you will be able to have many projects and host many website on our VPS. Hope you guys have refreshed your knowledge. Isn't installing and Configuring Django with Postgres, Nginx, and Gunicorn easy. If you still feel I have to add more points to it, don’t worry we will update more info. Stay connected to our page to update your knowledge.

Article Tools

Did this article help you?

YesNo

Become
an Author!

Write an Article