How to deploy a basic Django project on a Remote Server

Written by @kit.andres, Manually Translated by @ecoinstant

@coffeesource.net is a creation of @kit.andres and @ecoinstant, who are building out new tools upon the Steem Blockchain and promoting development through utopian.io within their communities.

We are working now on a Django deployment, so we decided to write a tutorial about this topic. In this tutorial we are going to deploy a Django project on a remote server; for this reason, this tutorial is for experienced users using Django, however we will try to solve all the doubts experienced by beginner users. We will use the project repository django_base (We created previously a tutorial about a django project starting), which will be configured using the following technologies:

nginx - Web/proxy server
gunicorn - Python applications server
PostgreSQL - Database engine
Ubuntu 16.04 server instance.

At the starting point of the tutorial we assume that you already have an Ubuntu Server 16.04 virtual instance (1) with a user with administrative privileges and git configured. In this tutorial, this previously created user is called admin.


In case we don't have a user with sudo permissions, we can create one with the following command, where admin is the name of the usere:

$ adduser admin

It will ask us for a strong password. The rest of the information it asks for after the password is not required. After, we can assign sudo privileges to the user with the following command:

$ usermod -aG sudo admin

1. Install software requirements on the server

The first step is to install the following libraries (pip, nginx y postgreSQL), keeping in mind that our Django project is made in Python 3.6.0.

$ sudo apt-get update
$ sudo apt-get install python3-pip python3-dev libpq-dev nginx postgresql postgresql-contrib

2. Clone Django

We clone the Django project that we want to start up with the following command (our project in github is called django_base):

git clone https://github.com/roadhousestudio/django_base

3. Create Database


Now we are going to create the database for our project. After installing postgreSQL in the previous step, we can start an interactive session with the following command:

$ sudo -u postgres psql

We create the database, in this case we'll name it django_base_db, and then create a user to access our database, giving it administrative privileges with the following commands:

postgres=# CREATE DATABASE django_base_db;
postgres=# CREATE USER djangouser WITH PASSWORD 'password';
postgres=# GRANT ALL PRIVILEGES ON DATABASE django_base_db TO djangouser;
postgres=# \q

4. Create virtual enviroment

We'll use virtualenv to start up the project. To install it, we should first install pip:

$ sudo -H pip3 install --upgrade pip
$ sudo -H pip3 install virtualenv

Now let's move to the root of the project (cd django_base/) and execute the following command, where we create a new virtual environment with the name djangoenv:

$ virtualenv djangoenv

We'll activate the virtual environment:

$ source djangoenv/bin/activate

5. Install Python libraries for the project

Now we will proceed to install the Python libraries required to build our project in the virtual environment, such as Django, psycopg2, and gunicorn.

(djangoenv)$ pip install django psycopg2 gunicorn

6. Configure settings for the project (DATABASES)

Now lets go to the file settings.py for our django project and edit the information about the database that we are going to use:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'django_base_db',
        'USER': 'djangouser',
        'PASSWORD': 'password,
        'HOST': 'localhost',
        'PORT': '',
    }
}

We also configure the setting ALLOWED_HOSTS:

ALLOWED_HOSTS = ['nombre de dominio o ip de instancia']

We execute the following command to create the tables of the database and then we deactivate the virtual environment:

(djangoenv)$ manage.py migrate
(djangoenv)$ deactivate

7. Configure gunicorn service

We are going to create a systemd file in order to activate gunircorn which will interact with our Django application. We should locate ourselves in the folder /etc/systemd/system/ and create the file django_base.service. We called it django_base so that it would have the same name as our Django project:

cd /etc/systemd/system/
sudo vim django_base.service

Inside the file django_base.service we add the following content:

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=deploy
Group=www-data
WorkingDirectory=/home/admin/django_base
ExecStart=/home/admin/django_base/django_env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/admin/django_base/django.sock app.wsgi:application
[Install]
WantedBy=multi-user.target




We save the file and activate the service through the following commands

$ sudo systemctl start django_base.service
$ sudo systemctl enable django_base.service

8. Configure nginx

Now we move to the folder /etc/nginx/sites-available/ and we create the file django_base (we created to have the same name as the repository):

$ cd /etc/nginx/sites-available/
$ sudo vim django_base

In the file we add the following content (remember, admin is the name of the administrator user):

server {
    listen       80;
    server_name   nombre-de-dominio-o-IP;
    charset      utf-8;

    client_max_body_size       10m;
    client_body_buffer_size    128k;

    # serve static files
    location /static/ {
        alias /home/admin/django_base/app/static/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/admin/django_base/django.sock;
    }
}

We save the changes made to the file and add a symbolic link inside the folder /etc/nginx/sites-enabled/

$ ln -s /etc/nginx/sites-available/django_base /etc/nginx/sites-enabled/

And finally we restart the service * nginx *:

$ sudo systemctl restart nginx

Now when we use a browser to visit the domain name or the ip of the remote instance that we indicated in the nginx configuration file we can see our Django application working.


This is all. The truth is it took us a bit of time at first to determine the procedure necessary to deploy a Django application on a remote server correctly, but now we know that the basic deployment consists of the steps that we just reviewed and it is done very easily and efficiently.

We will continue to share more information about the contribution to the development of open source projects, including a special new project close to our hearts.

Happy weekend for everybody!


(1) - Some hosting services, for example, are heroku, EC2, Linode, etc.


Love and Light to All!



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @coffeesource.net I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • You are generating more rewards than average for this category. Super!;)
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Congratulations @coffeesource.net! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

I am having trouble with the ./manage.py migrate step

Coin Marketplace

STEEM 0.28
TRX 0.13
JST 0.033
BTC 62916.93
ETH 3028.97
USDT 1.00
SBD 3.67