Deploy Django Web App with SSL on VPS using Nginx & Gunicorn
Published: 2024-05-04 12:30:59


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yqhtxq9ushds5o8ie43i.jpg)
Have you ever wanted to deploy your Django web application on a Virtual Private Server (VPS) with SSL encryption for secure communication? In this tutorial, we’ll walk through each step, from setting up prerequisites to configuring Nginx and Gunicorn, and finally securing your site with Let’s Encrypt SSL certificates.

**Prerequisites**:

Before we dive in, let’s ensure we have all the necessary tools and configurations in place.

First, we’ll need to create a requirements.txt file containing all the Python packages used in our project. We can easily generate this file using the pip freeze command.

`pip freeze > requirements.txt`
Next, we’ll set up static files using Whitenoise, a handy Django middleware for serving static files efficiently.

`pip install whitenoise`
Once installed, we’ll integrate Whitenoise into our Django project by adding it to the middleware list and configuring static file settings.

```
# settings.py
MIDDLEWARE = [
    ...
    "whitenoise.middleware.WhiteNoiseMiddleware",
    ...
]
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
```
With static files set up, let’s move on to deploying our project on a VPS.

## Deploying on VPS:

SSH into Your Server: First, SSH into your VPS by running:
`ssh username@server_ip_address`
2. Update & Upgrade Server:

`sudo apt-get update
sudo apt-get upgrade`
3. Install Python & Pip:

`
sudo apt install python3
sudo apt install python3-pip
`
4. Create & Activate Virtual Environment:

`virtualenv /opt/myproject
source /opt/myproject/bin/activate`
5. Clone Repository onto server:

`cd /opt/myproject
mkdir myproject
cd myproject
git clone repo-url`
6. Install Requirements (if any):

`cd repo-name
pip install -r requirements.txt
pip install gunicorn`
7. Nginx Configuration:

Install Nginx and configure it to serve your Django app:

`sudo apt install nginx
sudo nano /etc/nginx/sites-available/myproject`
Add the following configuration:

```
server {
    listen 80;
    server_name yourip;

    access_log /var/log/nginx/website-name.log;

    location /static/ {
        alias /opt/myproject/myproject/path-to-static-files/;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALLDSP COR PSAa PSDa OURNOR ONL UNI COM NAV"';
    }
}
```
Set up a symbolic link and restart Nginx:

`cd /etc/nginx/sites-enabled
sudo ln -s ../sites-available/myproject
sudo service nginx restart`
8. Testing Configuration:

Test your Nginx configuration and adjust the firewall settings:

`sudo nginx -t
sudo ufw allow 8000
sudo service nginx restart`
Now, run Gunicorn and visit your project on your server’s IP address:

`gunicorn --bind 0.0.0.0:8000 project_name.wsgi`
With your Django app successfully deployed on your VPS, you’re one step closer to making it accessible to the world. But wait, there’s more!

## Connecting a Domain:
To connect your project to a custom domain, follow these steps:

Open your domain registrar and navigate to the DNS settings for your domain.
Add an A record with the name “@” pointing to your server’s IP address.
Update your Nginx configuration to include your domain name.
Restart Nginx and wait for DNS changes to propagate.

## Securing with SSL:
Installing SSL Certificates with Let’s Encrypt:

Securing your website with SSL certificates is crucial for ensuring encrypted communication between your server and your users’ browsers. Let’s Encrypt provides free SSL certificates, making it accessible for everyone to enable HTTPS on their websites.

Here’s how you can install SSL certificates on your VPS using Let’s Encrypt:

1. Install Certbot:
`sudo apt install certbot`
`sudo apt install python3-certbot-nginx`
2. Obtain SSL Certificates:

Run Certbot with the --nginx option and specify your domain name(s) to obtain SSL certificates. Replace your_domain.com with your actual domain name.

`sudo certbot --nginx -d your_domain.com`
3. Verify Configuration:

`sudo nginx -t`
4. Reload Nginx:

`sudo systemctl reload nginx`
By following these steps, you’ll have successfully installed SSL certificates on your VPS using Let’s Encrypt, enabling secure HTTPS connections for your Django web application.

Background Process with Gunicorn:

Additionally, if you want to run Gunicorn in the background to keep your Django application running even after you log out of your SSH session, you can use the nohup command followed by & to run Gunicorn as a background process. This ensures that your application remains accessible even when you're not actively managing it.

Here’s how you can run Gunicorn in the background:

Run Gunicorn:
Navigate to your Django project directory and run Gunicorn with the appropriate bind address and port.

`cd /opt/myproject/myproject/repo-name
nohup gunicorn --bind 0.0.0.0:8000 project_name.wsgi &`
2. Check Process Status:

To verify that Gunicorn is running in the background, you can use the ps command to list all processes and grep for gunicorn.

`ps aux | grep gunicorn`
3. Stop Gunicorn Process:

If you ever need to stop the Gunicorn process running in the background, you can use the pkill command followed by gunicorn.

`pkill gunicorn`
Congratulations! Your Django web app is now deployed on a VPS with SSL encryption, ready to handle secure connections from users across the globe.

Conclusion:

In this tutorial, we’ve covered the entire deployment process, from setting up prerequisites to securing your site with SSL certificates. By following these steps, you can confidently deploy your Django projects on a VPS and provide a secure and reliable experience to your users.

Happy deploying!