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:
- Upgraded to a VPS or Dedicated hosting plan
- Configured a Proxy Server in the panel
- Installed a custom version of Python
- Created a virtual environment
- Set up your Gunicorn app in the virtual environment
- A subdomain was added to host your static assets.
- Created a Shell user and are able to log into your server via SSH
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.
- Create the following directories:
[server]$ mkdir -p ~/.config/systemd/user/
- Create a gunicorn.service file in the .config/systemd/user directory:
[server]$ nano ~/.config/systemd/user/gunicorn.service
-
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
- 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.
- Enable the user unit for gunicorn:
[server]$ systemctl --user enable gunicorn
- Start the unit with gunicorn:
[server]$ systemctl --user start gunicorn
- 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.