Systemd and Gunicorn

February 4, 2018

I've just updated my server from Debian 7 to Debian 9, and the previous configuration I was using to start and stop gunicorn isn't working. This post covers the new systemd based configuration.


In the /etc/systemd/system folder, create a new file for your service. In my case this is drumcoder.service.

Description=Drumcoder gunicorn daemon

ExecStart=/home/drumcoder/.venv/dc/bin/gunicorn --workers 1 --error-logfile /var/log/gunicorn/dc.log -b localhost:8001 -n drumcoder drum.drumcoder-wsgi:application


Most of this is self-expanatory. The Unit.After section defines when the service starts. Service.ExecStart is the command that is run to start the gunicorn process.

The parameters to ExecStart are:

  • /home/drumcoder/.venv/dc/bin/gunicorn - the path to the gunicorn binary
  • --workers 1 - number of workers for gunicorn
  • --error-logfile /var/log/gunicorn/dc.log - file to log errors to
  • -b localhost:8001 - where to listen for requests
  • -n drumcoder - name of process
  • drum.drumcoder-wsgi:application - path to wsgi

The final parameter on the ExecStart line points at the drumcoder-wsgi file inside the project. This is referenced here using the drum. prefix, as the file is located at /home/drumcoder/web/dc/drum/

The WSGI file contains:

import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'drumcoder.settingslive'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

import drumcoder.monitor


Once the drumcoder.service file is in place, the service can be controlled using the service command:

# service drumcoder stop
# service drumcoder start
# service drumcoder restart
# service drumcoder status

To make the service load automatically at boot time:

# systemctl enable drumcoder