Using linger with Gunicorn

 

Overview

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.

Prerequisites

This article assumes you have completed the following steps:

Step 1 — Installing 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 — Configuring 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:
    [Unit]
    Description=Gunicorn instance to serve application
    After=network.target
    
    [Service]
    WorkingDirectory=/path/to/your/app
    Environment="PATH=/path/to/venv/bin"
    ExecStart=/path/to/venv/bin/gunicorn --workers 3 --bind=<example.com>:<port> myapp:app
    ExecReload=/bin/kill -s HUP $MAINPID
    KillMode=mixed
    TimeoutStopSec=5
    PrivateTmp=true
    Restart=on-failure
    
    [Install]
    WantedBy=default.target
  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.
    • example.com: 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.

Configuring logging

You can configure access and error logging by modifying the gunicorn.service file created above. The code to point to your log files must be added to the ExecStart line. For example:

ExecStart=/path/to/venv/bin/gunicorn --workers 3 --bind=<example.com>:<port> --access-logfile /path/to/venv/bin/gunicorn/logs/gunicorn_access --error-logfile /path/to/venv/bin/gunicorn/logs/gunicorn_error --capture-output myapp:app

You only need to adjust the path to your logs directory. For example:

  • /path/to/venv/bin/gunicorn/logs/

Gunicorn will then create the access and error log files automatically using this code.

See also

Did this article answer your questions?

Article last updated PST.

Still not finding what you're looking for?