Django
Beginner
1 min read
Gunicorn and Nginx Configuration
Example
# Install Gunicorn
# pip install gunicorn
# Start Gunicorn (development test)
# gunicorn mysite.wsgi:application --bind 0.0.0.0:8000 --workers 3
# /etc/systemd/system/gunicorn.service
[Unit]
Description=Gunicorn daemon for mysite
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/mysite
ExecStart=/var/www/mysite/venv/bin/gunicorn \
--workers 5 \
--bind unix:/run/gunicorn/gunicorn.sock \
--timeout 120 \
--log-level warning \
--access-logfile /var/log/gunicorn/access.log \
--error-logfile /var/log/gunicorn/error.log \
mysite.wsgi:application
Restart=on-failure
[Install]
WantedBy=multi-user.target
# /etc/nginx/sites-available/mysite
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location /static/ {
alias /var/www/mysite/staticfiles/;
expires 1y;
add_header Cache-Control "public, immutable";
}
location /media/ {
alias /var/www/mysite/media/;
}
location / {
proxy_pass http://unix:/run/gunicorn/gunicorn.sock;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django