Django on VPS with Apache ubuntu and SSL: A Comprehensive Guide

L earn how to set up a secure Django application on an Apache server with SSL using Let's Encrypt and Certbot. Follow this comprehensive guide for a seamless deployment.

How to Install Django on a VPS with Ubuntu, Apache, and SSL
Setting up Django on a VPS running Ubuntu with Apache and SSL can seem daunting, but this comprehensive guide will walk you through the entire process step-by-step. By the end of this tutorial, you will have a secure and fully functional Django application running on your VPS. Step-by-Step Instructions to Install Django on Ubuntu VPS with Apache and SSL


Step 1: Update and Install Apache

First, update your package list and install Apache:

  sudo apt update
sudo apt install apache2
python3 --version
pip3 --version
git --version

sudo apt install apache2
sudo apt install python
sudo apt install libapache2-mod-wsgi-py3
sudo apt install python3-pip
sudo apt install git

pip list

sudo pip install virtualenv

# Verify Python installation:

    python3 --version

# Verify pip installation:

    pip3 --version

Step 2: Set Up Virtual Hosts (Recommended)

Create a directory for your Django project:

sudo mkdir /var/www/django.amankhalsa.in cd /var/www/django.amankhalsa.in

Assign ownership of the directory:

sudo chown -R $USER:$USER /var/www/django.amankhalsa.in sudo chmod -R 755 /var/www/django.amankhalsa.in

Create a sample index.html page:

nano index.html

Save and exit using Ctrl + O, Ctrl + X.

Create a new virtual host configuration file:

sudo nano /etc/apache2/sites-available/django_amankhalsa.conf

Paste in the following configuration block:

<VirtualHost *:80> ServerAdmin webmaster@localhost ServerName django.amankhalsa.in ServerAlias www.django.amankhalsa.in DocumentRoot /var/www/django.amankhalsa.in ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>

Using Nano

  1. Save Changes:

    • Press Ctrl + O (Write Out). This prompts you to save the file.
    • Press Enter to confirm the file name (or modify it if needed).
  2. Exit Nano:

    • Press Ctrl + X to exit the editor.

Using Vim

  1. Save Changes:

    • Press Esc to ensure you are in normal mode.
    • Type :w and press Enter to save the file.
  2. Exit Vim:

    • Type :q and press Enter to quit the editor.
    • To save and exit in one command, you can type :wq and press Enter.

Enable the new site configuration:

sudo a2ensite django_amankhalsa.conf

Disable the default site configuration:

sudo a2dissite 000-default.conf

Test for configuration errors:

sudo apache2ctl configtest

You should receive the following output:

Syntax OK

Restart Apache to apply the changes:

sudo systemctl restart apache2

Apache should now be serving your domain name. Check your IP in the browser:

http://216.10.242.119/

Step 3: Clone Project Repository

Make Connection between Remote Server and Github via SSH Key

- Generate SSH Keys

ssh-keygen -t rsa -b 4096 -C "admin@django.amankhalsa.in"

Move the private key (django_rsa) and public key (django_rsa.pub) into the .ssh directory:

 mv django_rsa django_rsa.pub ~/.ssh/

- Go to Your Github Repo

- Click on Settings Tab

- Click on Deploy Keys option from sidebar

- Click on Add Deploy Key Button and Paste Remote Server's Copied SSH Public Key then Click on Add Key

Run the following command to test the connection to GitHub using SSH:

eval $(ssh-agent -s)
ssh-add ~/.ssh/django_rsa
ssh -T git@github.com

Navigate to your project directory and clone the project: 

cd /var/www/django.amankhalsa.in sudo apt update sudo apt install git git --version git clone git@github.com:Amankhalsa/django_personal.git


Check files or for hidden files:

ls ls -a

Check permissions:

ls -l

Step 4: Install mod_wsgi

Install mod_wsgi to serve your Django application with Apache:

sudo apt install libapache2-mod-wsgi-py3

Step 5: Create a Virtual Environment and Install Dependencies

Navigate to your project directory and create a virtual environment:

cd /var/www/django.amankhalsa.in/django_personal python3 -m venv my_env source my_env/bin/activate pip install -r requirements.txt

The error you're encountering indicates that pkg-config is not installed, which is required for building certain Python packages that depend on native libraries (in this case, MySQL or MariaDB).
Steps to Resolve:

    Install pkg-config and the necessary development libraries for MySQL or MariaDB:

    Run the following command to install pkg-config and MySQL/MariaDB development headers:
  

sudo apt update
sudo apt install pkg-config libmysqlclient-dev


If you're using MariaDB, you can install the equivalent MariaDB development headers:

sudo apt install pkg-config libmariadb-dev


Activate your Python virtual environment (if not already active):

If you're using a virtual environment (e.g., my_env), make sure it's activated:

source /var/www/django.amankhalsa.in/django_personal/my_env/bin/activate


Reinstall the Python package:

Try installing the package again:

    pip install mysqlclient


This should resolve the issue and allow the installation of the necessary dependencies for your Django project.


Step 6: Configure Apache for Django

Create or edit the Apache configuration file for your Django project:

sudo nano /etc/apache2/sites-available/django_amankhalsa.conf

Paste in the following configuration block:

 # Configuration file for the Django project hosted on django.amankhalsa.in
    <VirtualHost *:80>
        # Admin email for this server (replace with your actual email)
        ServerAdmin admin@django.amankhalsa.in
        
        # The domain name for your site
        ServerName django.amankhalsa.in
        
        # The root directory of your Django project
        DocumentRoot /var/www/django.amankhalsa.in/django_personal
        # Alias for serving static files (CSS, JavaScript, images, etc.)
        Alias /static /var/www/django.amankhalsa.in/django_personal/staticfiles
        <Directory /var/www/django.amankhalsa.in/django_personal/staticfiles>
            # Grant access to static files
            Require all granted
        </Directory>
        # Alias for serving media files (user-uploaded content)
        Alias /media /var/www/django.amankhalsa.in/django_personal/media
        <Directory /var/www/django.amankhalsa.in/django_personal/media>
            # Grant access to media files
            Require all granted
        </Directory>
        # Directory settings for the main Django application directory
        <Directory /var/www/django.amankhalsa.in/django_personal/postfolio>
            # Allow access to wsgi.py file to serve the application
            <Files wsgi.py>
                Require all granted
            </Files>
        </Directory>
        # WSGI settings to run the Django application
        # Daemon process configuration with Python path and virtual environment
        WSGIDaemonProcess django_personal python-path=/var/www/django.amankhalsa.in/django_personal python-home=/var/www/django.amankhalsa.in/django_personal/my_env
        WSGIProcessGroup django_personal
        
        # The entry point for the WSGI application
        WSGIScriptAlias / /var/www/django.amankhalsa.in/django_personal/postfolio/wsgi.py
        # Log files for error and access logging
        ErrorLog ${APACHE_LOG_DIR}/django_amankhalsa_error.log
        CustomLog ${APACHE_LOG_DIR}/django_amankhalsa_access.log combined
    </VirtualHost>

Step 7: Enable the Apache Configuration

Enable the site and the wsgi module:

sudo a2ensite django_amankhalsa.conf sudo a2enmod wsgi

Step 8: Collect Static Files

Activate your virtual environment and collect static files:

source /var/www/django.amankhalsa.in/django_personal/my_env/bin/activate cd /var/www/django.amankhalsa.in/django_personal python manage.py collectstatic

Step 9: Apply Database Migrations

Apply the necessary database migrations:


python manage.py migrate

Step 10: Adjust Firewall Settings

Allow Apache through the firewall:


sudo ufw allow 'Apache Full'

Step 11: Secure Your Site with SSL (Optional but Recommended)

 Install Certbot and the Apache Plugin

Certbot is a tool that automates the process of obtaining and installing SSL certificates. Install Certbot and the Apache plugin using the following command:


sudo apt install certbot python3-certbot-apache

Run Certbot to obtain and install the SSL certificate:

sudo certbot --apache -d django.amankhalsa.in

Follow the prompts to complete the SSL certificate setup.

Step 12: Restart Services

Restart Apache to apply all changes:

sudo systemctl restart apache2

Step 13: Verify Your Setup

Visit https://django.amankhalsa.in to ensure your site is up and running with SSL.

0 Comments
Leave a Comment

Video