deploy django on nginx gunicorn

  1. Install required packages:
sudo apt-get update
sudo apt-get install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx
  1. Create a virtual environment:
sudo apt-get install virtualenv
mkdir ~/myproject
cd ~/myproject
virtualenv myprojectenv
source myprojectenv/bin/activate
  1. Install Django and Gunicorn:
pip install django gunicorn
  1. Create a Django project:
django-admin startproject myproject
cd myproject
  1. Configure Django settings (update ALLOWED_HOSTS, DEBUG, DATABASES):
# myproject/settings.py
ALLOWED_HOSTS = ['your_domain_or_server_ip', 'localhost']
DEBUG = False

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_db_name',
        'USER': 'your_db_user',
        'PASSWORD': 'your_db_password',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
  1. Migrate the database:
python manage.py migrate
  1. Create a superuser (optional):
python manage.py createsuperuser
  1. Collect static files:
python manage.py collectstatic
  1. Test the Gunicorn server:
gunicorn myproject.wsgi:application
  1. Configure Gunicorn to run as a systemd service:
sudo nano /etc/systemd/system/myproject.service

Add the following content:

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

[Service]
User=your_linux_username
Group=www-data
WorkingDirectory=/path/to/your/myproject
ExecStart=/path/to/your/myprojectenv/bin/gunicorn --workers=3 --bind unix:/path/to/your/myproject/myproject.sock myproject.wsgi:application

[Install]
WantedBy=multi-user.target
  1. Start and enable the Gunicorn systemd service:
sudo systemctl start myproject
sudo systemctl enable myproject
  1. Configure Nginx:
sudo nano /etc/nginx/sites-available/myproject

Add the following content:

server {
    listen 80;
    server_name your_domain_or_server_ip;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /path/to/your/myproject;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/path/to/your/myproject/myproject.sock;
    }
}
  1. Create a symbolic link to the Nginx configuration:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
  1. Test Nginx configuration and restart Nginx:
sudo nginx -t
sudo systemctl restart nginx
  1. Adjust firewall settings if needed:
sudo ufw allow 80
sudo ufw allow 8000  # If you want to access the Django development server
sudo ufw enable
  1. Update your DNS records if using a domain name.

Done! Your Django application should now be deployed with Nginx and Gunicorn.