Home » How to deploy a Django project using Nginx, Gunicorn, and Supervisor
sudo apt update
Next, install the required packages:
sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx
sudo -u postgres psql
CREATE DATABASE your_database_name;
CREATE USER your_username WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE your_database_name TO your_username;
q
git clone your_repository_url
python3 -m venv your_virtual_environment_name
source your_virtual_environment_name/bin/activate
Install the required Python packages for your Django project:
pip install -r requirements.txt
sudo nano /etc/nginx/sites-available/your_project_name
Add the following configuration to the file:
server {
listen 80;
server_name your_domain_name;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Enable the Nginx server block configuration:
sudo ln -s /etc/nginx/sites-available/your_project_name /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
sudo nano /etc/systemd/system/gunicorn.service
Add the following configuration to the file:
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=your_username
Group=www-data
WorkingDirectory=/path/to/your_project_directory
ExecStart=/path/to/your_virtual_environment_name/bin/gunicorn --access-logfile - --workers 3 --bind unix:/path/to/your_project_directory/your_project_name.sock your_project_name.wsgi:application
[Install]
WantedBy=multi-user.target
Enable and start the Gunicorn service:
sudo systemctl enable gunicorn
sudo systemctl start gunicorn
sudo nano /etc/supervisor/conf.d/your_project_name.conf
Add the following configuration to the file:
[program:your_project_name]
command=/path/to/your_virtual_environment_name/bin/gunicorn --access-logfile - --workers 3 --bind unix:/path/to/your_project_directory/your_project_name.sock your_project_name.wsgi:application
directory=/path/to/your_project_directory
user=your_username
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/path/to/your_project_directory/logs/gunicorn.log
Update Supervisor and start the process:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start your_project_name
python manage.py collectstatic
Restart Nginx and Supervisor for the changes to take effect:
sudo systemctl restart nginx
sudo supervisorctl restart your_project_name
Your Django project should now be successfully deployed on your VPS using Nginx, Gunicorn, Supervisor, and a PostgreSQL database. You can access your project by visiting your domain name in a web browser.