Deploy your Django Application to Digital Ocean using NGINX

Deploy your Django Application to Digital Ocean using NGINX

Lauch time! In this tutorial, I am going to show you how to deploy your Django application to Digital Ocean server.

I saw a lot of questions on StackOverflow about how to configure Nginx🔧 and questions about deploying Django project to Digital Ocean. However, I didn't find complete tutorials on the internet related to this topic. So, I decided to make a full tutorial to help developers to handle these situations.

I will explain it step by step because when I first tried to deploy my project I spent a lot of time to find solutions, so I don't want the same situation to happen to you. Alright! Enough talking. Let's launch your amazing Django🚀 rocket into production space!

Step 1: Connect to remote server

Initially, you have to connect your droplet or remote terminal by using this command:

ssh root@your_droplet_id

It will ask from you to enter the username (usually it is root) and UNIX password which both sent to your email. Then re-enter the same UNIX password and after type your own password which will let you connect your droplet.

Step 2: Install Python and pip

To install Python we must first update the APT repository using this command:

sudo apt-get update && sudo apt-get -y upgrade

The Django Software Foundation recommends using Python 3, so once everything is updated, the following command can be used to install Python 3:

sudo apt-get install python3

To verify the installation of Python 3, run a version check with the python3 command:

python3 -V

Output should look like python 3.5.2

Now that we have Python 3 installed, we will also need pip in order to install packages from PyPi, Python’s package repository.

sudo apt-get install -y python3-pip

To verify that pip was successfully installed, run the following command:

pip3 -V

Output should look like this pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5)

Alright! Now that we have pip installed, we can install other important packages for Python environment

Step 3: Install virtualenv

Virtualenv is a virtual environment where you can install Python packages and software in a contained development space that isolates the installed software and packages from the rest of the global environment of your machine.

For more details about virtualenv take a look Real Python's article Python Virtual Environments: A Primer

To install virtualenv, we will use the pip3 command:

pip3 install virtualenv

Now, check version to verify that the installation has completed successfully:

virtualenv --version

Output should look like this 15.1.0

You have successfully installed virtualenv. At this stage, we can isolate our Django web application from other Python packages on our system.

Step 3: Install Django

Django can be installed in three ways. For this tutorial, we will use the pip installation technique, but let's address all the alternatives available for your reference.

  • Option 1: Install Django within a virtualenv

    This is best way when you need to isolate your Django version from your server's global environment.

  • Option 2: Install Django from Source.

    You can install straight from source if you want the recent software or want something new than what your Ubuntu APT repository offers. Note that if you want your software version to be up to date, choosing this installation technique involves continuous attention and maintenance.

  • Option 3: Install Django Globally with pip.

    The option we are going with is pip 3 as we will be installing Django globally.

We will install Django using pip within a virtual environment.

Navigate to your home directory in your remote terminal and create the directory that will contain your Django application. Run the following command to create a directory called my-django-app, or another name of your choice. Then navigate to the directory.

mkdir my-django-app
cd my-django-app

While you are inside my-django-app directory, create your virtual environment. Let's call it venv:

virtualenv venv

Once it is created, activate the virtual environment with the following command:

. /venv/bin/activate

You will know it is activated when the prefix is changed to (venv), which will look similar to the following depending on what directory you are in:

(venv) coderasha@ubuntu:$

Now, it is time to install the Django package using pip:

(venv) coderasha@ubuntu:$ pip install django

Let's verify that Django installed successfully by following command:

django-admin --version

Output will look similar to this 2.2.4

Step 4: Install FileZilla and connect to remote site

At this stage, we are going to install FileZilla for transfer our project files to remote server.

If you are using Ubuntu you can directly install it from Ubuntu Software otherwise download it from official website FilleZilla.

Once you installed, open the FilleZilla and enter the required inputs. When you enter your droplet id in Host put sftp:// prefix to connect securely.

SFTP stands for SSH File Transfer Protocol, or Secure File Transfer Protocol, is a separate protocol packaged with SSH that works in a similar way over a secure connection.

Enter the Username (root) and Password that you created in Step 1. You can leave Port blank for now and click the Quickconnect button to connect your remote server.

Once you connected successfully, your remote directories will display right side of the window as shown in image below.

You successfully connected🔌 to your remote server!

Step 5: Transfer project files to remote server

While you are connecting, navigate to home directory in remote site. You can easily type /home/ as shown image below:

Step 5.1 : ALLOWED_HOSTS and DEBUG configuration

Before we transfer our project, we need to add our droplet_id to ALLOWED_HOSTS and change DEBUG Flase in settings.py

DEBUG = False
ALLOWED_HOSTS = ['your_droplet_id',]
With debug turned off Django won't handle static and media files for you anymore your production web server should take care of that. So, we will install Nginx and it will do the job for us. But before, one more important thing is collect static files and set up STATIC_ROOT.
Step 5.2: Set up STATIC_ROOT and collect static files

In your settings.py add following code:

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Then run the following command in your local terminal:

python3 manage.py collectstatic

Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.e. the STATIC_ROOT . In our case, we are telling Django that when we run python manage.py collectstatic , gather all static files into a folder called staticfiles in our project root directory.

You will see a new directory with name "staticfiles" in your Django project root directory.

That's it! Now, just simply select your Django project from your local site and drag inside the home directory of remote site.

Step 6: Install Nginx

Once you transferred your project, open your remote server terminal and deactivate virtual environment by following command:

deactivate

You will know it is deactivated when the prefix disappears. Now, navigate to your root directory and install nginx by commands below:

cd
sudo apt install nginx

Because Nginx is available in Ubuntu's default repositories, it is possible to install it from these repositories using the apt packaging system.

Step 7: Configure Nginx

While you are in remote server, navigate to default nginx site configuration to make small changes by following commands:

sudo nano /etc/nginx/sites-enabled/default

Nano is ideal for making small changes to existing configuration files or for writing short plain text files.

Delete all lines of code from the file and insert new configuration below:

server {
    listen 80;
    server_name your_droplet_ip:8000;

    root /var/www/html;

     location / {
             proxy_pass http://your_droplet_ip:8000;
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_set_header Host $http_host;
             proxy_set_header X-NginX-Proxy true;

    }

    location /static/admin {
             alias  /path/to/staticfiles/admin/;
}
    location /static/ {
             alias  /path/to/staticfiles/;
}


   location /media/ {
    autoindex on;
    alias /path/to/media/; 
     }    
}

Then Ctrl + O to save and Ctrl + X to exit

  • location /static/admin

    location for serving Django Administration static files.

  • location /static/

    location for serving static files

  • location /media/

    location for serving media files

If a request ends with a slash, NGINX treats it as a request for a directory and tries to find an index file in the directory. The index directive defines the index file’s name (the default value is index.html). To continue with the example, if the request URI is /images/some/path/, NGINX delivers the file /www/data/images/some/path/index.html if it exists. If it does not, NGINX returns HTTP code 404 (Not Found) by default. To configure NGINX to return an automatically generated directory listing instead, include the on parameter to the autoindex directive:
The NGINX alias directive defines a replacement for the specified location.
Note:

If this option does not work properly for you and nginx still not serving static files try to change location /static/, path to alias /path/to/static/ and copy admin folder from inside staticfiles directory then paste it inside of static directory. Once you paste it change location /static/admin, path to alias /path/to/static/admin/

Step 8: Restart Nginx and run server

So far we done everything for successful launch and now it is time to run server and make your Django Application live!

Restart the nginx by following command:

service nginx restart

After, navigate to my-django-app directory and activate the virtual environment as I showed before. Finally, navigate inside your Django application and run following command:

python3 manage.py runserver your_droplet_ip:8000

That's it! You just successfully launched your Django Rocket!

Step 9: Install Screen

Screen or GNU Screen is a terminal multiplexer. In other words, it means that you can start a screen session and then open any number of windows (virtual terminals) inside that session. Processes running in Screen will continue to run when their window is not visible even if you get disconnected.
Screen Documentation

screen allows us to resume the sessions or long-running tasks on a remote machine

The screen package is pre-installed on most Linux distros nowadays. You can check if it is installed on your system by typing:

screen --version

If you don’t have screen installed on your system, you can easily install it using the package manager of your distro.

sudo apt install screen

To start a screen session, simply type screen in your console:

screen

Now run Django server in this virtual terminal then Ctrl + a d and you will return original terminal but server still run background

Mission Accomplished!👨‍🚀

This was a long tutorial😅 but you learned how to deploy your awesome apps to Digital Ocean server!

If you liked the tutorial please share it with friends and see you in very next post DEVs!