Using linger with Gunicorn


This article explains how to use the Python linger package with the Gunicorn WSGI server. This combination allows your app to run persistent processes and your services to restart if your app crashes or the server reboots.

You must be on a VPS or Dedicated hosting plan to install the software in these instructions.


This article assumes you have completed the following steps:

Step #1: Install linger

To install linger under your user, log in to your server via SSH and run the following command:

[server]$ loginctl enable-linger

This command will not respond with any output.

Step #2: Configure Gunicorn

This step configures Gunicorn to work with systemd user units on the server.

  1. Create the following directories:
    [server]$ mkdir -p ~/.config/systemd/user/
  2. Create a gunicorn.service file in the .config/systemd/user directory:
    [server]$ nano ~/.config/systemd/user/gunicorn.service
  3. Add the following code to this file:
    Description=Gunicorn instance to serve application
    ExecStart=/path/to/venv/bin/gunicorn --workers 3 --bind=<>:<port> myapp:app
    ExecReload=/bin/kill -s HUP $MAINPID
  4. Edit the highlighted lines above as follows:
    • WorkingDirectory: The path to your website application.
    • Environment: The path to your virtual environment.
    • ExecStart: The path to your gunicorn installation.
    • Your website name.
    • port: The port number you configured in your Proxy Server.
    • myapp: The name of your application.

    View Running Gunicorn for further information.

  5. Enable the user unit for gunicorn:
    [server]$ systemctl --user enable gunicorn
  6. Start the unit with gunicorn:
    [server]$ systemctl --user start gunicorn
  7. Confirm it is running:
    [server]$ systemctl --user status gunicorn

Your app's services will now automatically restart when the server reboots or if the application crashes.

See also

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?