How to Deploy a Django Application to Digital Ocean

  • Akshay Pawar
  • Oct 6, 2021
django rest framework , django , digital ocean

Create an account

Create a new account on the Digital Ocean by using the below link


DigitalOcean Referral Badge


Download MobaXterm

To access SSH and FTP on your server, we need a software called MobaXtream Software. Click on the link below to download: Download MobaXterm


Digital Ocean Setup

1. Add the project name, and description, and select the purpose of the project.

2. Then create a new droplet. Basically in the digital ocean a server or service that you want to use they're called droplets

3. Select droplet settings according to your convenience. For example

4. Select Ubuntu 20.04 x64

5. Choose a starter plan from the plan list (you can choose any plan according to your requirements).

6. You can add backups to your droplet (Again it depends upon you, whether you want to enable it or not)

7. Select a data center region ( Select datacenter that is closer to you and your end-users)

8. Select One-time password Authentication to sign in to your server. Later we will enable SSH private key authentication, In order to do that, we need a one-time password (Please note down the password you are setting somewhere safe).

9. After that select how many droplets you need, add tags and select a project from the dropdown menu to assign droplets to a project.


MobaXterm Setup

1. Open and click on the new session (SSH).

2. Copy the IP address of the newly created droplet and paste it into the remote host input box and specify the root as the username. It will create a new terminal under session and prompt you to enter your droplet password

3. Create a non-root user using this command, adduser oxvsys it will create a new non-root user (folder) under the home folder. Enter the password for the new user and skip for other user info (press enter).

4. Add permission to the non-root user usermod -aG sudo oxvsys.


Setup SSH private keys

1. Open a command prompt on your computer.

2. Generate SSH keys for both root and non-root users using the command, ssh-keygen and change the key name to root and non-root user respectively. (e.g. id_rsa to root and id_rsa.pub to root.pub)

3. Copy the content of root.pub key and goto root/.ssh folder and open the authorized_keys file with a default text editor and paste it into.

4. For non-root users copy the content of non-root.pub key goto home/oxvsys folder and create .ssh folder, within that folder, create an authorized_keys file and paste it into it.

5. To ensure that you are authenticating with keys and you can test that using a command on your computer ssh oxvsys@<ip-address> and type yes and enter a user's password.

6. You can also test this with MobaXterm. Create a new session (SSH) > copy the IP address of the droplet into the remote host input box and specify the user name. > goto Advanced SSH settings > click on Use private key and browse user private ssh key that your previously generated, click on ok and you will authenticate using an ssh key.


Disable Password-based Authentication

1. Before disabling the password-based authentication, please ensure that your private ssh key-based authentication is working and keep your ssh keys safe, take a backup of it.

2. To disable password-based authentication sudo nano /etc/ssh/sshd_config that's gonna open up that file and look for PasswordAuthentication yes and set it to no then ctrl+x to exit > then press y for yes > then press enter.


Setting Up a Basic Firewall

1. sudo ufw app list - it will show available applications.

2. sudo ufw allow openssh- to allow it.

3. sudo ufw enable to enable the firewall, then press y to proceed.

4. sudo ufw status to check the status of what is currently active.


Installing Python, pip3, and set python version

1. supo apt update

2. sudo apt install python3.9

3. To set the priority of the existing version of python to level 2

4. sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2

5. To set the priority of the required version of python to level 1

6. sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.9 1

7. To set the python version I want to use sudo update-alternatives --config python. It will you choices to select, choose selection number from the choice list which has a priority level equivalent to level 1.

8. To install pip sudo apt-get install -y python3-pip

9. To check whether pip is installed or not, type pip3


Create a virtual environment and Django project

1. Install virtualenv sudo -H pip3 install virtualenv

2. Navigate to /home/oxvsys directory cd /home/oxvsys

3. Create a directory for the Django project mkdir djangoprojectdir

4. Create a virtual environment virtualenv djangoprojectenv inside that directory

5. Activate environment source djangoprojectenv/bin/activate

6. Install Gunicorn and Django pip install gunicorn django

7. Either create a new project or Copy your existing Django project from your machine and paste it into djangoprojectdir directory.

8. Install dependencies pip install -r requirements.txt

9. Some libraries are os dependent, so make sure you install os dependent library (e.g. on windows if we want to install pyscopg2 we just type a command pip install psycopg2, but on Linux, you will get an error, in that case, you will need Linux-dependent dependencies, then use pip install psycopg2-binary)

10. You will get an error while installing pyodbc library, for that case install sudo apt-get install unixodbc-dev.

11. Add localhost and IP address of your droplet into ALLOWED_HOSTS

12. Change database settings according to your preferences and make migrations python manage.py makemigrations & migrate it python manage.py migrate

13. Run command python manage.py collectstatic

14. To allow port 8000 through the firewall - sudo ufw allow 8000

15. To run the server python manage.py runserver 0.0.0.0:8000

16. Remember this is just for testing, we are testing Gunicorn right now. Later we will Nginx to run the server automatically.

17. Check your server is running by typing droplet IP-address:8000 into the browser (e.g. 192.168.0.1:8000).

18. Now we run the server manually and Gunicorn is working correctly, it's able to run the server alone without us typing the command to run the server gunicorn --bind 0.0.0.0:8000 app.wsgi.


Gunicorn socket and service

1. We will create a system socket & all the services for Gunicorn, and Nginx to run the server without us having to run the server by using the command.

2. We're not gonna be using a virtual environment, not running runserver manually, we're gonna be relying on Nginx & Gunicorn to run/host the server.

3. Deactivate the virtual environment deactivate

4. Install everything onto the server that we just installed in a virtual environment pip3 install -r requirements.txt

5. Some libraries are os dependent, so make sure you install os dependent library (refer to step no 9 from the above section)

6. Make sure you logged in as a root user, Navigate to etc/systemd/system the folder, and create gunicorn.socket a config file. and paste the following code as it is and do not change anything.

   [Unit]Description=gunicorn socket
   
   [Socket]ListenStream=/run/gunicorn.sock
   
   [Install]WantedBy=sockets.target

7. Create gunicorn.service file and paste the following code and change the code according to your project settings.

       [Unit]
       Description=gunicorn daemon
       Requires=gunicorn.socketAfter=network.target
       
       [Service] User=oxvsys
       Group=www-data
       WorkingDirectory=/home/oxvsys/djangoprojectdir
       ExecStart=/home/oxvsys/djangoprojectdir/djangoprojectenv/bin/gunicorn \
                  --access-logfile - \
                  --workers 3 \
                  --bind unix:/run/gunicorn.sock \
                  app.wsgi:application
                   
       [Install] 
       WantedBy=multi-user.target


8. First, we need to start the socket and then service

        sudo systemctl start gunicorn.socket
        sudo systemctl enable gunicorn.socket

9. To check whether the socket is working correctly, use the command - file /run/gunicorn.sock. You can also check whether the file is generated or not by looking inside the run directory.

10. If the gunicorn.sock file is not generated then try this command sudo shutdown -r now. It will shut down your server and reset it.

11. To check the status of the socket after enabled sudo systemctl status gunicorn.socket

12. To test the socket activation mechanism, we can send a connection to the socket curl by typing curl --unix-socket /run/gunicorn.sock localhost. If this command runs correctly you will see HTML as output.

13. If you change gunicorn.service or shutdown the server

        sudo systemctl daemon-reload
        sudo systemctl restart gunicorn.socket gunicorn.service

14. To the status of Gunicorn service sudo systemctl status gunicorn


Configure Nginx to Proxy Pass to Gunicorn

1. Install Nginx sudo apt install nginx

2. Navigate to /etc/nginx/sites-available/. Create a file named, djangoproject then add the following code

    server {
        listen 80;
        server_name server_domain_or_IP;

        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            root /home/oxvsys/djangoprojectdir;
    }

        location / {
            include proxy_params;
            proxy_pass http://unix:/run/gunicorn.sock;
        }
    }

3. Now link this file to sites-enabled a folder and it will generate a file inside sites-enabled the folder.

       sudo ln -s /etc/nginx/sites-available/djangoproject /etc/nginx/sites-enabled

4. To check Nginx setup by running sudo nginx -t.

5. To restart Nginxsudo systemctl restart nginx.

6. Change firewall port to allow Nginx instead of port 8000, that's what we are doing for testing.

        sudo ufw delete allow 8000	  
        sudo ufw allow 'Nginx Full'

7. That will allow traffic through your firewall through Nginx.


Congratulations

We have deployed our Django app on Digital Ocean successfully. Stay tuned for the next part where we will register the domain name for our app and set up HTTPS Digital Ocean Ubuntu Server.

Copyright © 2024 Oxvsys Automation Technologies Pvt. Ltd.