sudo to restart gunicorn

March 31, 2011

My gunicorn process runs as a user that doesn't own the files that make up the Django app it's serving. I wanted a way to be able to restart the gunicorn process (kill -HUP pid) without having to become that user in a shell. In this way it's possible to script the restart as part of the file release. I also wanted this unattended and so not need a password.

We can do this using sudo

sudoers

First we need to edit the sudoers file. This shouldn't be edited directly, use visudo as root to edit.

# visudo

By default the file only contains the following on Debian:

Defaults        env_reset
root    ALL=(ALL) ALL

We need to add a row in here which allows a given user to run /bin/kill as a different user, without a password. This can be done with the following, where drumcoder is the user owning the files, and server is the user that gunicorn runs as:

drumcoder ALL=(server) NOPASSWD:NOEXEC: /bin/kill

One at a command prompt as user drumcoder, you can now run the following command to restart the gunicorn process:

$ sudo -u server kill -HUP gunicorn_pid

Tags: sudo sudoers gunicorn