Deploying Your Django App with Gunicorn and Nginx
Deploying your Django app is a crucial step in making it accessible to users. This guide outlines a straightforward process using Gunicorn as the application server and Nginx as a reverse proxy to serve your Django app.
1. Set Up a Virtual Environment
Ensure isolation of project dependencies by creating and activating a virtual environment:
python -m venv venv source venv/bin/activate # On Unix/MacOS# source venv\Scripts\activate # On Windows
2. Install Django and Dependencies
Install Django and required packages:
pip install django gunicorn psycopg2-binary
3. Configure Database
Update your Django app's settings.py to use the appropriate production database, e.g., PostgreSQL:
# settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'yourdbname', 'USER': 'yourdbuser', 'PASSWORD': 'yourdbpassword', 'HOST': 'localhost', 'PORT': '5432', } }
4. Collect Static Files
Collect static files into a directory for easier serving:
python manage.py collectstatic
5. Configure Django Settings
Adjust your settings.py for production. Set DEBUG to False and update ALLOWED_HOSTS :
# settings.py
DEBUG = False ALLOWED_HOSTS = ['yourdomain.com']
6. Use Gunicorn as the Application Server
Run your Django app using Gunicorn:
gunicorn yourapp.wsgi:application
sudo apt-get install nginx sudo nano /etc/nginx/sites-available/yourapp
Add the configuration:
server { listen 80; server_name yourdomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/your/static/directory; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } }
Enable the Nginx site and restart the server:
sudo ln -s /etc/nginx/sites-available/yourapp /etc/nginx/sites-enabled sudo nginx -t sudo systemctl restart nginx
8. Configure Gunicorn as a Systemd Service
Create a systemd service for Gunicorn:
sudo nano /etc/systemd/system/yourapp.service
Add the configuration:
[Unit] Description=gunicorn daemon for yourapp After=network.target [Service] User=youruser Group=yourgroup WorkingDirectory=/path/to/your/app ExecStart=/path/to/venv/bin/gunicorn --workers=3 --bind unix:/path/to/your/app/yourapp.sock yourapp.wsgi:application [Install] WantedBy=multi-user.target
Enable and start the Gunicorn service:
sudo systemctl enable yourapp sudo systemctl start yourapp
Conclusion
Following these steps carefully simplifies the deployment of your Django app using Gunicorn and Nginx, ensuring it runs smoothly in a production environment.