Gunicorn (short for Green Unicorn) is a robust, production-grade WSGI HTTP server for Python web applications.
It’s lightweight, has no external dependencies, and is widely used for deploying Django apps behind a proxy like Nginx.
In this guide, I'll walk you through how to install and run Gunicorn as your WSGI server for a Django project.What is Gunicorn?
Gunicorn is a pre-fork worker model server that handles multiple requests by spawning worker processes. It acts as the interface between your Django application and the web server (like Nginx), ensuring efficient request handling and scalability.Installing Gunicorn
To install Gunicorn, use pip -
python -m pip install gunicorn
For more detailed configuration options, you can also consult the official Gunicorn documentation.
Running Gunicorn with Django
After installing Gunicorn, agunicorn
command becomes available in your terminal. To serve your Django app, navigate to the root directory of your project (where manage.py
is located) and run-gunicorn myproject.wsgi
- Start the Gunicorn server
- Bind it to 127.0.0.1:8000 by default
- Use the application object from myproject/wsgi.py
Static and Media Files with Gunicorn
Gunicorn does not serve static or media files in a production environment. That's where Nginx comes in. You’ll want to configure Nginx to serve:
/static/
→ for static files likeCSS/JS
/media/
→ for uploaded content
settings.py
accordingly -# settings.py
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
python manage.py collectstatic
Bonus Tips
- Consider using a process manager like systemd or supervisor to keep Gunicorn running in the background.
- Use the --workers flag to scale Gunicorn for concurrent users
gunicorn myproject.wsgi --workers 3
Conclusion
Gunicorn is a reliable and high-performance WSGI server that integrates seamlessly with Django. While it doesn’t servestatic/media
content on its own, it works perfectly behind Nginx to create a production-ready deployment stack.Next up: Configuring Nginx to reverse proxy to Gunicorn.