Running with Gunicorn
Serve Django in production with a WSGI server like Gunicorn.
Syntax
gunicorn mysite.wsgi:applicationNever run runserver in production. Instead use a real WSGI application server such as Gunicorn, which serves your project's wsgi module with multiple worker processes. Put a web server like Nginx in front to handle HTTPS and static files.
Example
# Install
pip install gunicorn
# Run the WSGI app (mysite/wsgi.py)
gunicorn mysite.wsgi:application --bind 0.0.0.0:8000 --workers 3
# For async projects, use an ASGI server instead:
# pip install uvicorn
# uvicorn mysite.asgi:applicationWhen to use it
- A developer replaces the Django dev server with Gunicorn to serve the app under real production load.
- A DevOps engineer runs Gunicorn with multiple workers behind an Nginx reverse proxy for a production deployment.
- A team writes a systemd service file to keep Gunicorn running as a daemon that restarts on server reboot.
More examples
Run Gunicorn with workers
Starts Gunicorn with 4 worker processes bound to port 8000, logging access to stdout.
# pip install gunicorn
gunicorn mysite.wsgi:application \
--workers 4 \
--bind 0.0.0.0:8000 \
--access-logfile -Nginx proxy to Gunicorn
Configures Nginx to serve static files directly and forward all other requests to Gunicorn.
# /etc/nginx/sites-available/mysite
server {
listen 80;
server_name mysite.com;
location /static/ { root /var/www/mysite; }
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}Gunicorn config file
Stores Gunicorn settings in a Python config file for cleaner deployment scripts.
# gunicorn.conf.py
workers = 4
worker_class = "gthread"
threads = 2
bind = "0.0.0.0:8000"
timeout = 30
accesslog = "-"
errorlog = "-"
Discussion