Gunicorn is a “Python WSGI HTTP Server for UNIX”. It is absolutely stupid simple to setup and get running.
I will be using the following for this guide:
- Django 1.8
- Debian 8 (jessie)
pip3 install gunicorn
Create a blank WSGI file inside your project folder (where
manage.pyresides). This is where you can configure Gunicorn options instead of passing arguments to it.
gunicorn --threads=COUNT PROJECT.wsgi:application
That’s it. You now have a Gunicorn WSGI server running on port
The Gunicorn docs recommend setting the thread count to 2x to 3x the core count of the server.
After install Gunicorn and testing it out, you’ll probably want to set it up as a service so it can be started automatically on boot.
Create a new user.
Give it an extremely long and random password. You won’t be logging into this user.
Move your Django project into
/home/django/. This is now where your project will reside.
Change the ownership of your project files.
chown -R django:django /home/django/
Update the static files path in nginx if you have one set.
Create the Gunicorn systemd service file.
nano /etc/systemd/system/gunicorn.service123456789101112131415161718[Unit]Description=gunicorn daemonRequires=gunicorn.socketAfter=network.target[Service]Environment=PYTHONHASHSEED=randomPIDFile=/run/gunicorn/pidUser=djangoGroup=djangoWorkingDirectory=/home/django/PROJECTExecStart=/usr/local/bin/gunicorn --pid /run/gunicorn/pid django.wsgi:applicationExecReload=/bin/kill -s HUP $MAINPIDExecStop=/bin/kill -s TERM $MAINPIDPrivateTmp=true[Install]WantedBy=multi-user.target
Create the Gunicorn systemd socket file.
nano /etc/systemd/system/gunicorn.socket12345678910[Unit]Description=gunicorn socket[Socket]ListenStream=/run/gunicorn/socketListenStream=0.0.0.0:9000ListenStream=[::]:8000[Install]WantedBy=sockets.target
Change the permissions so the pid file can be created.
chown -R django:django /run/gunicorn
Start the services.12systemctl start gunicorn.socketsystemctl start gunicorn.service
Enable the services to be started on boot if there were no problems.12systemctl enable gunicorn.socketsystemctl enable gunicorn.service
- Update any cronjobs for Django to the new user.
- Change file permissions of the static files if you are not running nginx as the
I had one small issue with Redis where the user had no permission to access
/var/run/redis.sock. This was easily solved by using TCP sockets instead of Unix sockets.