How to Use Gunicorn with Django: Simple Setup Guide
To use
gunicorn with Django, first install Gunicorn with pip install gunicorn. Then run your app using gunicorn myproject.wsgi:application to serve your Django project with Gunicorn's production-ready server.Syntax
The basic command to run Gunicorn with Django is:
gunicorn <project_name>.wsgi:application: Starts Gunicorn using the WSGI application of your Django project.--bind <address>: Optional flag to specify the IP and port to listen on (default is 127.0.0.1:8000).--workers <num>: Optional flag to set the number of worker processes for handling requests.
bash
gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 --workers 3
Example
This example shows how to run a Django project named myproject with Gunicorn, binding to all network interfaces on port 8000 and using 3 worker processes.
bash
pip install gunicorn cd myproject gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 --workers 3
Output
Starting gunicorn 20.x.x
Listening at: http://0.0.0.0:8000
Using worker: sync
Booting worker with pid: 12345
Common Pitfalls
- Not installing Gunicorn: Forgetting to install Gunicorn causes command not found errors.
- Wrong project name: Using incorrect Django project name in the command leads to import errors.
- Running Gunicorn in development: Gunicorn is for production; use
python manage.py runserverfor development. - Not configuring allowed hosts: Ensure
ALLOWED_HOSTSinsettings.pyincludes your server IP or domain.
bash
Wrong command example: gunicorn wrongproject.wsgi:application Right command example: gunicorn myproject.wsgi:application
Quick Reference
Remember these tips when using Gunicorn with Django:
- Install Gunicorn with
pip install gunicorn. - Run Gunicorn with your Django project's WSGI module.
- Use
--bindto set IP and port. - Use
--workersto improve performance. - Configure
ALLOWED_HOSTSproperly in Django settings.
Key Takeaways
Install Gunicorn using pip before running it with Django.
Run Gunicorn with your Django project's WSGI module to serve the app.
Use --bind to specify the server address and --workers to set worker count.
Configure ALLOWED_HOSTS in Django settings to avoid host errors.
Gunicorn is for production; use Django's runserver for development.