Skip to main content





How to Host a Django Application on a VPS

How to Host a Django Application on a VPS

If you have built a Django application and you are ready to take it live, choosing the right hosting environment is one of the most important decisions you will make. Django VPS hosting offers a powerful, flexible, and cost-effective solution for developers who want full control over their server environment without the expense of a dedicated server. In this guide, we will walk you through every step of hosting a Django application on a Virtual Private Server (VPS), from initial setup to going live.

Why Choose a VPS for Django Hosting?

A Virtual Private Server gives you a dedicated slice of a physical server, complete with your own resources, operating system, and root access. Unlike shared hosting, which can throttle your application’s performance and limit your configuration options, a VPS allows you to install any software you need, configure your environment precisely, and scale your resources as your application grows.

Django VPS hosting is particularly well-suited for Python-based web applications because you have the freedom to manage your Python version, virtual environments, and dependencies without restriction. For developers who want more control than platforms like Heroku offer, but do not yet need a full dedicated server, a VPS sits in the perfect middle ground.

Prerequisites Before You Begin

Before diving into the setup process, make sure you have the following in place:

  • A VPS from a reputable provider (Ubuntu 22.04 LTS is recommended)
  • A registered domain name pointed to your VPS IP address
  • SSH access to your server
  • A working Django application with a requirements.txt file
  • Basic familiarity with the Linux command line

Step 1: Update Your Server and Install Dependencies

Once you have logged into your VPS via SSH, the first thing you should do is update the package list and upgrade existing packages. This ensures your server is secure and running the latest software.

sudo apt update && sudo apt upgrade -y

Next, install the essential packages you will need for Django VPS hosting:

sudo apt install python3 python3-pip python3-venv nginx git ufw -y

You will also want to install PostgreSQL if your Django application uses it as a database:

sudo apt install postgresql postgresql-contrib libpq-dev -y

Step 2: Set Up a PostgreSQL Database

Creating the Database and User

Switch to the PostgreSQL user and open the PostgreSQL shell:

sudo -i -u postgres
psql

Inside the shell, create a new database and user for your Django application:

CREATE DATABASE myprojectdb;
CREATE USER myprojectuser WITH PASSWORD 'securepassword';
ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE myprojectuser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE myprojectdb TO myprojectuser;
\q

Exit the PostgreSQL user session and return to your regular user account.

Step 3: Deploy Your Django Application

Cloning Your Project

Navigate to the directory where you want to store your application, typically /var/www/, and clone your project from a Git repository:

cd /var/www/
sudo git clone https://github.com/yourusername/yourproject.git
cd yourproject

Setting Up a Virtual Environment

Create and activate a Python virtual environment to keep your project’s dependencies isolated:

python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install gunicorn psycopg2-binary

Configuring Django Settings

Update your Django settings file to reflect the production environment. Set DEBUG = False, add your domain to ALLOWED_HOSTS, and configure your database settings to point to the PostgreSQL database you created. It is best practice to use environment variables for sensitive information such as your secret key and database credentials.

Run migrations and collect static files:

python manage.py migrate
python manage.py collectstatic

Step 4: Configure Gunicorn

Gunicorn is a Python WSGI HTTP server that sits between your Django application and Nginx. It handles incoming requests and passes them to Django for processing. Create a systemd service file to manage Gunicorn:

sudo nano /etc/systemd/system/gunicorn.service

Add the following content, adjusting paths to match your project:

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/yourproject
ExecStart=/var/www/yourproject/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock yourproject.wsgi:application

[Install]
WantedBy=multi-user.target

Enable and start the Gunicorn service:

sudo systemctl start gunicorn
sudo systemctl enable gunicorn

Step 5: Configure Nginx as a Reverse Proxy

Nginx will act as the front-facing web server, handling static files and forwarding dynamic requests to Gunicorn. Create a new Nginx configuration file for your site:

sudo nano /etc/nginx/sites-available/yourproject

Add the following configuration:

server {
    listen 80;
    server_name yourdomain.co.uk;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {
        root /var/www/yourproject;
    }

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

Enable the configuration and restart Nginx:

sudo ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx

Step 6: Secure Your Server with SSL

A production Django application must use HTTPS. Install Certbot to obtain a free SSL certificate from Let’s Encrypt:

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.co.uk

Certbot will automatically configure Nginx to redirect HTTP traffic to HTTPS and renew your certificate automatically.

Step 7: Configure the Firewall

Use UFW to allow only the necessary ports:

sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable

Best Practices for Django VPS Hosting

Once your application is live, there are several best practices you should follow to keep it running smoothly and securely:

  • Keep your server updated: Regularly apply security patches and updates to your operating system and Python packages.
  • Use environment variables: Never hardcode sensitive credentials in your settings file. Use tools like python-decouple or django-environ.
  • Monitor your application: Set up logging and monitoring tools so you can identify and resolve issues quickly.
  • Back up your database: Schedule regular database backups to avoid data loss in the event of a server failure.
  • Scale when needed: A VPS allows you to upgrade your plan as traffic grows, making it a scalable solution for growing projects.

For more helpful guides on web hosting, server management, and Django deployment, visit the DA Manager blog, where you will find a wealth of resources for developers and system administrators alike.

Final Thoughts

Hosting a Django application on a VPS might seem daunting at first, but by following these steps carefully, you can have a robust, secure, and scalable production environment up and running in a matter of hours. Django VPS hosting gives you the control and flexibility that modern web applications demand, without locking you into the constraints of managed hosting platforms. Whether you are launching a small personal project or a growing commercial application, a well-configured VPS is an excellent foundation for your Django deployment.