Internet of Things

Setting up Django, Gunicorn and Nginx in Raspian Jessie using Raspberry Pi 2.

This article will show you how we have actually setup a Django, Gunicorn, Nginx web server using Raspbian Jessie Operating System. Let's start by looking at the pre-requisite and actual implementation!

Check OS Version

It is important that we check the OS version of the OS installed on the Pi. This will help us on the next step.
Enter the following command at shell
$ cat /etc/os-release or $ lsb_release -a

Set OS configuration

$ sudo raspi-config

Check for updates

We will run $ sudo apt-get update to have the latest updates to be installed on the Pi

Upgrade to OS

Once we download the updates earlier, we need to upgrade them using the following command.
$ sudo apt-get upgrade

Install XRDP to allow remote access to Jessie GUI (Optional)

This is optional, unless you require remote access to the Jessie GUI.
You may run this command $ sudo apt-get install xrdp

Install necessary components (e.g. PostgresSQL, Nginx)

We will be using PostgresSQL in this setup example
You may run this command$ sudo apt-get install python-dev libpq-dev postgresql postgresql-contrib nginx
to begin the installation of PostgresSQL, Nginx and other required packages.


Check Postgres Installation

To check whether Postgres is installed properly,
You may run this command $ sudo su – postgres



You may access the postgres database by running the following command: $ psql


We will proceed to create the database for our example, to do that.
First, we will create a database named mywebproject, by running the following command:
$ CREATE DATABASE mywebproject;
Next, we will a user to be used for the project solely, you may do that by doing this command:
$ CREATE USER mywebprojectuser WITH PASSWORD 'Password1';
Finally, we will need to grant the privileges in order to use the user account we just created.
You may do so by this command: $ GRANT ALL PRIVILEGES ON DATABASE mywebproject TO mywebprojectuser;
Remember to quit the Postgres console: $ \q Quit the postgres logged in: $ exit Here is how it looks like:

Update the root password

In this example, we are using root account, hence we are updating the root password.
You may run this command $ sudo passwd root to update the password

Install the virtual environment

We will need to log in as root to install the virtual environment, but before we can do that we will need to install virtualenv.
To do so, please run pip install # pip install virtualenv

Create the web project

To begin setting up the project, we will need to create a directory to be used, let's call it mywebproject
You can create it simply by # mkdir ~/mywebproject to have the directory created
Now, we need to go into the directory, by # cd ~/mywebproject.

We are going to create virtual environment to contain the project in this setup, and going to make sure of the virtualenv to do so. Run the following command:
1. # virtualenv mywebprojectenv
The virtual environment is created.
Before we can use the environment, we will need to activate it.
2. # source mywebprojectenv/bin/activate

Install Gunicorn

We will continue to be in the virtual environment, proceed to install the Gunicorn, and its dependencies by running # pip install django gunicorn psycopg2

Start the Django project

Create a django project named mywebproject, by running the command: # django-admin.py startproject mywebproject .
Remember to be in the project directory we created. This is how it looks like:

Configure the settings for Django

To use the Postgres database properly with the web project, we will need to configure the settings file
You will need to edit the settings.py file inside the web project directory by running # nano mywebproject/settings.py
You will need to go to the DATABASES section, here is the edited content:
DATABASES = {
    'default': {
      'ENGINE': 'django.db.backends.postgresql_psycopg2',
      'NAME': 'mywebproject',
      'USER': 'mywebprojectuser',
      'PASSWORD': 'Password1',
      'HOST': 'localhost',
      'PORT': '',
    }
}



You will also need to configure the static to tell the web server how to render static files.
There is only one section to do that: STATIC_ROOT = os.path.join(BASE_DIR, "static/")

Write the changes made to Django project and Database

After we have make the necessary, we need to write them into the Django web project as well as create the first schema for database
Remember to be in the project directory we created.
# cd ~/mywebproject
Run the following command to commit the changes made to settings.py
# ./manage.py makemigrations We need to create the first database schema for Django. Run this command.
# ./manage.py migrate

Create superuser for Django Admin

In order to manage the Django objects via the admin console, we will need to create a superuser account to login.
You may run this command: # ./manage.py createsuperuser
You just need to follow the screen to enter the email (remember to enter a valid email address), password, and confirm the password you just entered.

Collect the static files created for Django

Remember the setting you have done on the settings.py, you would need to set it to point correctly to the static directory where static files are stored.
To do so, run this command: # ./manage.py collectstatic

Start the Django server and test it.

Now that Django settings, database are set up. We can proceed to start the Django server and test it.
To do so, run this command: # ./manage.py runserver 0.0.0.0:8000


If you notice, the django server is running on default port (8000), if there is no error message, you should see the following page displayed:


Configure Gunicorn to use Nginx to run Django automatically

In order for us to use Gunicorn for Nginx and Django, we will need to bind the web project with wsgi service.
You may run the following commands to do so: (remember to stay in the virtual environment when you do these. # cd ~/mywebproject - go into the project directory
# gunicorn --bind 0.0.0.0:8000 mywebproject.wsgi:application
# deactivate - deactivate to come up from the virtual environment.

Configure the Gunicorn service

We will configure the gunicorn service by running # nano /etc/systemd/system/gunicorn.service
This is the settings that will be change:
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=/home/root/mywebproject
ExecStart=/home/root/mywebproject/mywebprojectenv/bin/gunicorn --workers 3 --bind unix:/home/root/mywebproject/mywebproject.sock mywebproject.wsgi:application

[Install]
WantedBy=multi-user.target


Enable and Start the Gunicorn service

We will enable the gunicorn service by running # systemctl enable gunicorn
Next, start the gunicorn service by running # systemctl start gunicorn

Configure Nginx service for the web server

In order for us to use Nginx and Django, we will need to set some setting on nginx.conf
You may run the following commands to do so:
# nano /etc/nginx/nginx.conf - edit the conf file
This is the settings:
    server  {
           listen 80;
           server_name 192.168.1.44;

           location = /favicon.ico { access_log off; log_not_found off; }
           location /static/ {
              root /home/root/mywebproject;
}
           location / {
              proxy_set_header Host $http_host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto $scheme;
              proxy_pass http://unix:/home/root/mywebproject/mywebproject.sock;
           }
    }
}

Test the Nginx service

We will first test that Nginx config file is free of syntax error# nginx -t
If there is no error message returned, proceed to the next step:

Enable and Start the Nginx service

We will enable the nginx service by running # systemctl enable nginx
Next, start the nginx service by running # systemctl start nginx.

Test the web site

Go to your web site by typing http://serverIP at your desired web browser.
If there is no error message, you will see the following screen:

What's next?

We can use this web server to serve up your own website. Watch out for more updates on this article