Deploy Django: Digital Ocean Hosting Unleashed

This guide empowers Django developers to master the art of deploying their applications on Digital Ocean. Discover step-by-step instructions, best practices, and tips for a seamless deployment experience, ensuring optimal performance and scalability

image description

Deploy Django: Digital Ocean Hosting Unleashed

In this guide, we'll walk you through the process of deploying a Django demo app on Digital Ocean, one of the most popular cloud hosting providers. We'll cover setting up SSL for secure communication, configuring domain settings using either Google Domains or GoDaddy, and creating a new non-root user for enhanced security. For our setup, we'll be using SQLite as the default database, Apache2 as the web server, Git for version control, and a requirements.txt file for handling dependencies.

Why Django and Digital Ocean?

Before we dive into the deployment process, let's take a moment to understand why Django and Digital Ocean make a winning combination. Django, known for its pragmatic design and clean, reusable code, empowers developers to build complex web applications swiftly. Its batteries-included philosophy provides a wide range of built-in tools, enabling you to focus on your application's unique features rather than reinventing the wheel.

On the other hand, Digital Ocean stands out as a preferred hosting solution for many developers due to its user-friendly interface and cost-effective pricing. Whether you are a seasoned professional or a newcomer to server management, Digital Ocean offers a seamless experience for setting up and managing cloud servers, allowing you to concentrate on your Django app's performance and scalability.

Prerequisites:

Before proceeding with the deployment and update of your Django application on Digital Ocean, make sure you have the following:

  1. Django App: Preparing Your Django App for Deployment

  2. Digital Ocean Account: Sign up for a Digital Ocean account to create and manage virtual droplets (servers).

  3. Git Repository: Your Django application should be hosted in a Git repository, like GitHub, Bitbucket, or GitLab.

  4. Domain Name (Optional): If you want to use a custom domain for your application, you should have a registered domain name from either Google Domains or GoDaddy.

  5. Basic Understanding of Django: Familiarity with Django web framework and its project structure is necessary to follow the deployment process.

  6. SSH Key (Optional): Generating an SSH key pair is recommended for secure access to your Digital Ocean droplet.

  7. Ubuntu 20.04 Droplet: Create a new droplet on Digital Ocean using the Ubuntu 20.04(x64) LTS distribution as the operating system.

Now that you have the prerequisites in place, let's proceed with the deployment and update process: 

In this guide, we will be setting up the subsequent Django app: Food expiry app

DigitalOcean Sign Up If you don't have a DigitalOcean account yet, you can sign up using the link below and receive $200 credit for 60 days to get started:

Start your free trial with a $200 credit for 60 days

(Note: This is a referral link, meaning both you and I will get credit.)

DigitalOcean Referral Badge

Preparing Your Django App for Deployment

To ensure a smooth deployment process, it's essential to prepare your Django application adequately. Let's take a look at some of the key steps involved:

1. Handling Static Files

In Django, static files such as CSS, JavaScript, and images need to be served separately from dynamic content. To achieve this, we use the collectstatic command, which gathers all static files from various locations in your Django project and places them in a single directory.

python manage.py collectstatic

For example, if you have a CSS file named styles.css in your app's static/css directory, running collectstatic will place it in the STATIC_ROOT directory (specified in your settings), making it accessible to the webserver.

2. Configuring the Database Settings

During development, you might have used a local database like SQLite. In the production environment, it's crucial to use a more robust database system like PostgreSQL or MySQL. Update your Django project's settings to use the appropriate database backend and connection settings.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database_name',
        'USER': 'your_database_user',
        'PASSWORD': 'your_database_password',
        'HOST': 'localhost',
        'PORT': '',
    }
}

For example, if you are using PostgreSQL, you need to install the necessary package on your server:

PostgreSQL

Install the dependencies to use PostgreSQL with Python/Django:

sudo apt update
sudo apt-get -y install build-essential libpq-dev python-dev

Install the PostgreSQL Server:

sudo apt-get -y install postgresql postgresql-contrib

3. Optimizing for Production

Adjust your Django settings for optimal performance in a production environment. Set DEBUG to False, update the ALLOWED_HOSTS with your server's IP or domain name, and consider using a caching mechanism like Redis to speed up your app.

DEBUG = False
ALLOWED_HOSTS = ['your_server_ip', 'your_domain.com']

Additionally, consider using Gunicorn or uWSGI as the application server in front of your Django app to handle incoming web requests. These servers are designed for production use and can provide better performance and scalability than Django's built-in development server.

4. Managing Environment Variables

Keep sensitive information, such as secret keys and API credentials, secure by using environment variables. You can use the python-decouple library to read environment variables from a .env file.

pip install python-decouple

In your Django settings:

from decouple import config

SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)

This way, you can store sensitive information in the .env file on your server, separate from your codebase.

Set Up the Digital Ocean Droplet

Setting up your Digital Ocean account is straightforward, and we'll guide you through the process. Follow these steps:

  1. Go to the Digital Ocean website (https://www.digitalocean.com/) and sign up for an account.
  2. Once logged in, click on "Create" and select "Droplets" from the dropdown menu.
  3. And choose an image for your droplet. For Django, select a Linux distribution such as Ubuntu.

  1. Tailor the droplet size to meet your application's needs. For smaller projects, a standard droplet will suffice, while larger applications may demand more resources.

  1. Selecting a data center strategically can significantly reduce latency and enhance user experience.

  1. Choose between SSH keys or password-based authentication for secure access.

  1. If needed, explore additional options like backups and monitoring to enhance your server's capabilities.

  1. Finally, take the momentous step and click "Create Droplet" to deploy your virtual server.

Once you've made your decision, take action by clicking on the magical "Create" button. Witness the birth of your newly minted droplet as it gracefully appears in your profile.

Upon receiving the root password through email, proceed by selecting the appropriate IP Address to access the server via SSH:

ssh root@64.227.168.26

Upon your initial login, you'll be prompted to modify the root password.

For Unix-like OS users, you can access the server using the terminal. Meanwhile, if you are using Windows, you may opt to download PuTTY.

Alternatively, you have the option to use Digital Ocean's console if that suits your preference:

This way, you can conveniently manage your server through the method that best fits your setup.

Step 1: Set Up the Digital Ocean Droplet [Sort steps for creating droplet]

  1. Log in to your Digital Ocean account and click on "Create Droplet."
  2. Choose an image with Django pre-installed (if available) or select a Linux distribution of your choice.
  3. Select the desired server size and region. For small projects, the basic option should be sufficient.
  4. Add your SSH key for secure access.
  5. Click on "Create Droplet" to deploy your server.

Step 2: Initial Server Configuration

  1. Connect to your Droplet via SSH: ssh root@your_droplet_ip
  2. Create a new non-root user: adduser your_username
  3. for limited user : create/add user for limited privillages:
root@localhost:~# adduser jai
Adding user `jai' ...
Adding new group `jai' (1000) ...
Adding new user `jai' (1000) with group `jai' ...
Creating home directory `/home/jai' ...
Copying files from `/etc/skel' ...
New password: 
Retype new password: 
passwd: password updated successfully
Changing the user information for jai
Enter the new value, or press ENTER for the default
	Full Name []: jai
	Room Number []: 
	Work Phone []: 
	Home Phone []: 
	Other []: 
Is the information correct? [Y/n] y
root@localhost:~# 

 

  1. Grant administrative privileges: usermod -aG sudo your_username
  2. Secure SSH by editing /etc/ssh/sshd_config, set PermitRootLogin no, and restart SSH: sudo service ssh restart.
  3. Update packages: sudo apt update && sudo apt upgrade
  4. Install Apache2: sudo apt install apache2
  5. Configure the firewall: sudo ufw allow OpenSSH && sudo ufw enable

Step 3: Clone the Django Demo App

  1. Install Git: sudo apt install git
  2. Navigate to the desired directory: cd /var/www
  3. Clone the Django demo app repository: git clone https://github.com/django/django.git demo_app

OR

Step 4: Copy your Django project files to the droplet using scp

To transfer files from your local machine to the droplet using scp, follow these steps:

  1. Open your terminal or command prompt on your local machine.

  2. Use the scp command with the source file or directory and the destination on the droplet:

    scp -r /path/to/your/local/project username@droplet_ip:/path/on/droplet

     

  3. Replace /path/to/your/local/project with the path to your Django project files on your local machine.

  4. Replace username with your droplet's username, droplet_ip with the droplet's IP address, and /path/on/droplet with the directory path on the droplet where you want to copy the files.

  5. Enter your droplet's password or use your SSH key if prompted.

  6. The files will be securely copied to the droplet, and you can now access your Django project on the server.

Step 5: Set Up Python Virtual Environment

  1. Install Python3 and pip: sudo apt install python3 python3-pip
  2. Install virtualenv: sudo apt install python3-venv
  3. Create a virtual environment: python3 -m venv myenv
  4. Activate the virtual environment: source myenv/bin/activate
root@demo-host-name % source venv/bin/activate
(venv) jai@demo-host-name % 

Step 6: Configuring PostgreSQL Database

Switch to the PostgreSQL user:

To switch to the PostgreSQL user, open your terminal and enter the following command:

su - postgres

Create a database user and the application database:

Once you are logged in as the PostgreSQL user, you can create a new database user and the corresponding application database. Let's assume the new user is called username and the database is named dbname.

To create the user, run the following command:

createuser username

Next, let's create the application database dbname and set username as the owner:

createdb dbname --owner username

Now, we need to set a password for the newly created user username. We will use '123' as an example password, but it's essential to choose a strong and secure password in a real scenario.

psql -c "ALTER USER username WITH PASSWORD '123'"

Note: Please ensure to pick a strong and secure password for your application in practice. The usage of '123' here is only for simplicity's sake.

Switch back to the root user:

To return to the root user, simply use the following command:

exit

After following these steps, you should have a PostgreSQL database configured with a new user (username) and database (dbname) ready for your application's use.

Step 7: Install Dependencies and Set Up the Database

  1. Navigate to the Django demo app directory: cd /var/www/demo_app
  2. Install requirements: pip install -r requirements.txt
  3. Apply migrations: python manage.py migrate
  4. Create a superuser: python manage.py createsuperuser

Step 8: Configure Apache2 and Enable the Django App

  1. Create an Apache2 configuration file: sudo nano /etc/apache2/sites-available/demo_app.conf
  2. Add the following content (replace your_domain.com with your domain):
<VirtualHost *:80>
 ServerName your_domain.com
 ServerAdmin your_email

 Alias /static /var/www/demo_app/static
 <Directory /var/www/demo_app/static>
     Require all granted
 </Directory>

 <Directory /var/www/demo_app/demo>
     <Files wsgi.py>
         Require all granted
     </Files>
 </Directory>

 WSGIDaemonProcess demo_app python-home=/var/www/demo_app/myenv python-path=/var/www/demo_app/demo
 WSGIProcessGroup demo_app
 WSGIScriptAlias / /var/www/demo_app/demo/wsgi.py

 ErrorLog ${APACHE_LOG_DIR}/error.log
 CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
  1. Enable the site: sudo a2ensite demo_app
  2. Reload Apache: sudo service apache2 reload

Step 9: Set Up SSL Certificate (Let's Encrypt)

1. Visit this link: To get started with Let's Encrypt and learn more about their services, please visit the official Let's Encrypt website by clicking on the following link: Let's Encrypt.

2. Install Let's Encrypt Certbot on Ubuntu with Apache: If you are using Ubuntu Focal Fossa and Apache as your web server, you can obtain and install Let's Encrypt certificates using Certbot. To do this, follow the instructions provided on the Certbot website. Click on the following link to access the guide for installing Let's Encrypt Certbot on Ubuntu with Apache: Certbot - Let's Encrypt - Ubuntu Focal Fossa - Apache.

Feel free to explore the links and follow the instructions to secure your website with Let's Encrypt certificates.

  1. Install Certbot: sudo apt install certbot python3-certbot-apache
  2. Obtain and install the SSL certificate: sudo certbot --apache -d your_domain.com

Step 10: Configure Domain Settings (Google Domains)

1. Log in to your Google Domains account.

  • Go to the Google Domains website (domains.google.com).
  • Click on the "Sign In" button and enter your Google account credentials.

2. Go to the DNS management page for your domain.

  • After logging in, you should see a list of domains associated with your account.
  • Find the domain for which you want to configure the settings and click on it.

3. Add an "A" record with your Droplet's IP address.

  • An "A" record maps a domain or subdomain to an IPv4 address (i.e., your server's IP address).
  • On the DNS management page, look for the section to add new records.
  • Select "A" from the record type dropdown menu.
  • In the "Name" or "Host" field, enter the desired domain or subdomain (e.g., your_domain.com or subdomain.your_domain.com).
  • In the "IPv4 Address" field, enter your Droplet's IP address.
  • Save the record to apply the changes.

Example: Suppose your Droplet's IP address is 203.0.113.45, and you want to point the main domain "example.com" to your Droplet. You would add an "A" record like this:

  • Name/Host: @ or leave it blank (for the main domain)
  • IPv4 Address: 203.0.113.45

4. Add a "CNAME" record for the "www" subdomain (if desired) pointing to your domain.

  • A "CNAME" record creates an alias for one domain or subdomain to point to another domain's canonical name (i.e., your main domain).
  • Still on the DNS management page, find the section to add new records.
  • Select "CNAME" from the record type dropdown menu.
  • In the "Name" or "Host" field, enter "www" (without quotes) to set up the "www" subdomain.
  • In the "CNAME" or "Value" field, enter your main domain (e.g., your_domain.com).
  • Save the record to apply the changes.

Example: If you want to create a "www" subdomain that points to the main domain "example.com," you would add a "CNAME" record like this:

  • Name/Host: www
  • CNAME/Value: example.com

Step 11: Configure Domain Settings (GoDaddy)

1. Log in to your GoDaddy account.

  • Go to the GoDaddy website (www.godaddy.com).
  • Click on the "Sign In" button and enter your GoDaddy account credentials.

2. Access the DNS management page for your domain.

  • After logging in, you should see a list of domains associated with your account.
  • Find the domain for which you want to configure the settings and click on it.

3. Add an "A" record with your Droplet's IP address.

  • Similar to the process in Google Domains, an "A" record in GoDaddy will map a domain or subdomain to your server's IP address.
  • Look for the section to add new DNS records.
  • Select "A" from the record type dropdown menu.
  • In the "Host" field, enter the desired domain or subdomain (e.g., your_domain.com or subdomain.your_domain.com).
  • In the "Points to" or "IP Address" field, enter your Droplet's IP address.
  • Save the record to apply the changes.

Example: Suppose your Droplet's IP address is 203.0.113.45, and you want to point the main domain "example.com" to your Droplet. You would add an "A" record like this:

  • Host: @ or leave it blank (for the main domain)
  • Points to/IP Address: 203.0.113.45

4. Add a "CNAME" record for the "www" subdomain (if desired) pointing to your domain.

  • Again, similar to Google Domains, a "CNAME" record in GoDaddy creates an alias for one domain or subdomain to point to another domain's canonical name (i.e., your main domain).
  • Find the section to add new DNS records.
  • Select "CNAME" from the record type dropdown menu.
  • In the "Host" field, enter "www" (without quotes) to set up the "www" subdomain.
  • In the "Points to" or "CNAME" field, enter your main domain (e.g., your_domain.com).
  • Save the record to apply the changes.

Example: If you want to create a "www" subdomain that points to the main domain "example.com," you would add a "CNAME" record like this:

  • Host: www
  • Points to/CNAME: example.com

Step 12: Automatic SSL Certificate Renewal

Let's Encrypt certificates automatically renew every 90 days. You can check the status with: sudo certbot renew --dry-run

Step 13: Access Your Django Demo App

  1. Add your domain to the Django demo app's allowed hosts.
  2. Restart Apache: sudo service apache2 restart
  3. Visit your domain (e.g., your_domain.com) in a web browser to see the Django demo app in action!

Ref Link for Linux Commands: 

Reference Link : Comprehensive Linux Tutorial for Beginners with Linux Distro List [Link]

Conclusion

Congratulations! You've successfully deployed the Django demo app on Digital Ocean with SSL, domain configuration through Google Domains or GoDaddy, and enhanced security using a non-root user. Your web project is now accessible securely through your custom domain. Keep exploring Django and building amazing web applications. Happy coding!

DigitalOcean Referral Badge

DigitalOcean Sign Up : If you don't have a DigitalOcean account yet, you can sign up using the link below and receive $200 credit for 60 days to get started: Start your free trial with a $200 credit for 60 days link below: Get $200 free credit on DigitalOcean ( Note: This is a referral link, meaning both you and I will get credit.)


Latest From PyDjangoBoy

👩💻🔍 Explore Python, Django, Django-Rest, PySpark, web 🌐 & big data 📊. Enjoy coding! 🚀📚