Introduction
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this guide, we'll walk through the steps to set up Django with Postgres, Nginx, and Gunicorn on Ubuntu.
Prerequisites
Before proceeding, ensure you have:
- An Ubuntu server
- SSH access to your server
Steps to Set Up Django with Postgres, Nginx, and Gunicorn
- Install Required Packages: Install required packages for Django and database:
sudo apt update
sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx
- Create PostgreSQL Database and User: Log in to the PostgreSQL shell and create a database and user:
sudo -u postgres psql
CREATE DATABASE mydatabase;
CREATE USER myuser WITH PASSWORD 'mypassword';
ALTER ROLE myuser SET client_encoding TO 'utf8';
ALTER ROLE myuser SET default_transaction_isolation TO 'read committed';
ALTER ROLE myuser SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;
\q
- Install Django and Create Project: Install Django using pip and create a Django project:
sudo -H pip3 install django
django-admin startproject myproject
- Configure Django Settings: Configure the database settings in the Django project's settings.py file.
- Set Up Gunicorn: Install Gunicorn and create a systemd service file:
sudo -H pip3 install gunicorn
sudo nano /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=your_username
Group=www-data
WorkingDirectory=/path/to/your/django/project
ExecStart=/path/to/your/virtualenv/bin/gunicorn --workers 3 --bind unix:/path/to/your/django/project/myproject.sock myproject.wsgi:application
[Install]
WantedBy=multi-user.target
- Start and Enable Gunicorn: Start and enable the Gunicorn service:
sudo systemctl start gunicorn
sudo systemctl enable gunicorn
- Set Up Nginx: Configure Nginx as a reverse proxy for Gunicorn:
sudo nano /etc/nginx/sites-available/myproject
server {
listen 80;
server_name your_domain www.your_domain;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /path/to/your/django/project;
}
location / {
include proxy_params;
proxy_pass http://unix:/path/to/your/django/project/myproject.sock;
}
}
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx
Conclusion
Congratulations! You have successfully set up Django with Postgres, Nginx, and Gunicorn on your Ubuntu server. You can now deploy your Django web application and serve it using Gunicorn and Nginx.