How To Set Up Secure Django with Postgres, Nginx, and Gunicorn on Ubuntu

Search for a command to run...

No comments yet. Be the first to comment.
Deploying a Django project on cPanel is a great way to get your app online without needing a VPS or cloud server. Whether your code is hosted on GitHub or you have the files on your local machine, this step-by-step guide will help you deploy it easil...

Ensuring your website is secure is crucial, especially if it involves sensitive data exchanges or user authentication. Moving from HTTP to HTTPS not only improves the trustworthiness of your website but also ensures it meets the best security standar...

Creating documentation for a Flutter project involves several key components. Here’s a step-by-step guide to help you through the process: 1. Project Overview Project Name: Include the name of your Flutter project. Introduction: Provide a brief des...

Creating an e-commerce app in Flutter can be a rewarding experience, especially with Flutter's powerful toolkit that enables the development of high-quality cross-platform mobile applications. Whether you’re a beginner or an experienced developer, th...

Django is a robust web framework designed to help you rapidly build Python applications or websites. While Django provides a simplified local development server, you’ll need a more secure and scalable server setup for production environments.
This guide will walk you through setting up Django on Ubuntu 22.04 (or a supported version) with a PostgreSQL database. We’ll configure the Gunicorn application server to interface with your Django app and set up Nginx to reverse proxy to Gunicorn, leveraging its security and performance benefits. Additionally, we’ll deploy the application from GitHub using DigitalOcean’s App Platform, allowing automatic scaling and management.
By isolating Django within a virtual environment, you’ll be able to handle project dependencies independently. Once your database and application are live, Gunicorn will translate client requests into Python calls. Nginx will manage connections and serve static files efficiently.
Let’s dive into setting everything up!
Ensure you’re using Ubuntu 22.04 or newer, as older versions like 16.04 are no longer supported. Follow our server setup guide to create a non-root user with sudo privileges and an active firewall.
Install Packages from Ubuntu Repositories
Create PostgreSQL Database and User
Set Up a Python Virtual Environment
Create and Configure Your Django Project
Complete the Django Setup
Test Gunicorn’s Ability to Serve Django
Create Gunicorn systemd Socket and Service Files
Check Gunicorn Socket File
Configure Nginx to Proxy Gunicorn
Troubleshoot and Complete Setup
Start by updating your package lists and installing the required packages:
sudo apt update
sudo apt install python3-venv python3-dev libpq-dev postgresql postgresql-contrib nginx curl
This will install Python, PostgreSQL, and Nginx, alongside development libraries and tools required for your project.
Set up your PostgreSQL database and user:
postgres user and access PostgreSQL:sudo -u postgres psql
CREATE DATABASE myproject;
CREATE USER myprojectuser WITH PASSWORD 'password';
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 myproject TO myprojectuser;
\q
Create a virtual environment and install Django:
mkdir ~/myprojectdir
cd ~/myprojectdir
python3 -m venv myprojectenv
source myprojectenv/bin/activate
pip install django gunicorn psycopg2-binary
django-admin startproject myproject .
ALLOWED_HOSTS in myproject/settings.py:ALLOWED_HOSTS = ['your_server_domain_or_IP', 'localhost']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myproject',
'USER': 'myprojectuser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
python manage.py migrate
python manage.py createsuperuser
python manage.py collectstatic
sudo ufw allow 8000
python manage.py runserver 0.0.0.0:8000
Visit http://your_server_domain_or_IP:8000 in your browser to verify that Django is running.
Stop the Django development server and test Gunicorn:
gunicorn --bind 0.0.0.0:8000 myproject.wsgi
systemd Socket and Service FilesCreate socket and service files for Gunicorn:
sudo nano /etc/systemd/system/gunicorn.socket
Add the following content:
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
sudo nano /etc/systemd/system/gunicorn.service
Add this content:
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=your_user
Group=www-data
WorkingDirectory=/home/your_user/myprojectdir
ExecStart=/home/your_user/myprojectdir/myprojectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
myproject.wsgi:application
[Install]
WantedBy=multi-user.target
sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn.socket
Verify that Gunicorn started properly:
sudo systemctl status gunicorn.socket
You should see a message indicating that the socket is active.
Check for the socket file:
file /run/gunicorn.sock
If there’s an issue, check the logs:
sudo journalctl -u gunicorn.socket
sudo nano /etc/nginx/sites-available/myproject
Add this content:
server {
listen 80;
server_name your_server_domain_or_IP;
location / {
proxy_pass http://unix:/run/gunicorn.sock;
}
location /static/ {
alias /home/your_user/myprojectdir/static/;
}
}
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx
If you encounter any issues, check Nginx’s error log:
sudo journalctl -u nginx
And Gunicorn’s logs:
sudo journalctl -u gunicorn
If everything is working, your Django application should now be live, served via Nginx and Gunicorn with PostgreSQL as the database backend!