Sub topic 11
Keeping the app running with systemd
Gunicorn only serves requests while its process is alive. A crash, a reboot, or a closed SSH session ends it. This chapter puts Gunicorn under systemd, the service manager on current Debian and Ubuntu servers, so the app starts at boot and comes back after failures.
This chapter assumes you can edit files as root with sudo, have a working Gunicorn command like the one in the previous chapters, and know the basics of systemctl. PHP-FPM needs no unit file from you. The php8.3-fpm package installs and enables its own, so the same systemctl and journalctl commands below apply to it.
What systemd does for your app
systemd starts a service in the right order, runs it as a chosen user, records its output, and restarts it according to a policy. It tracks every process the service starts in a control group (cgroup), so a stop command reliably ends Gunicorn's master process and all of its workers.
The unit file
Save this as /etc/systemd/system/myapp.service. Files in this directory are yours. Files under /lib/systemd/system belong to packages.
[Unit]
Description=Gunicorn for myapp
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/srv/myapp
RuntimeDirectory=gunicorn
ExecStart=/srv/myapp/venv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn/app.sock app:application
Restart=on-failure
[Install]
WantedBy=multi-user.targetEach directive does one job.
| Directive | Purpose |
|---|---|
| `After=network.target` | Orders startup after basic networking. It does not make the service depend on it. |
| `User=`, `Group=` | Drops privileges. The process never runs as root. |
| `WorkingDirectory=` | Sets the current directory, so `app:application` imports from `/srv/myapp`. |
| `RuntimeDirectory=gunicorn` | Creates `/run/gunicorn` owned by the service user at start and removes it at stop. |
| `ExecStart=` | The command. Use absolute paths. |
| `Restart=on-failure` | Restarts after a non-zero exit, a fatal signal, or a timeout. |
| `WantedBy=multi-user.target` | Makes `enable` start the service at normal boot. |
Why absolute paths and no shell
systemd does not run ExecStart through a shell. Pipes, &&, ~, and $HOME do not work. Calling /srv/myapp/venv/bin/gunicorn directly uses the virtual environment without activating it, because that script's interpreter line points into the venv.
Why RuntimeDirectory
/run is a memory-backed filesystem that is empty after each boot. A manually created /run/gunicorn would vanish at reboot and Gunicorn would fail to bind its socket. RuntimeDirectory recreates the directory on every start.
Starting, enabling, and inspecting
After you create or edit a unit file, systemd must reread it.
sudo systemctl daemon-reload
sudo systemctl enable --now myapp.service
systemctl status myapp.service
ls -l /run/gunicorn/enable creates the boot-time link. --now also starts the service immediately. The status output shows the state, the main PID, the control group's processes, and the last log lines. The ls command confirms the socket exists.
Read the full log with journalctl.
journalctl -u myapp.service -n 50 --no-pager
journalctl -u myapp.service -fGunicorn writes to stderr by default, and systemd sends both stdout and stderr to the journal. You do not need a log file for basic use.
Restart policy
Restart= controls what happens when the process ends.
| Value | Restarts after clean exit | Restarts after crash or signal | Restarts after `systemctl stop` |
|---|---|---|---|
| `no` | No | No | No |
| `on-failure` | No | Yes | No |
| `always` | Yes | Yes | No |
Stopping a service yourself never triggers a restart under any policy. For an app server that should never exit, on-failure works. always also covers the case where something exits with status 0 unexpectedly.
Add a delay to avoid hammering a broken dependency:
[Unit]
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Restart=on-failure
RestartSec=2RestartSec=2 waits two seconds between attempts. If the service is started more than five times within 60 seconds, systemd stops trying and marks it failed. The start-limit settings belong in [Unit], which is a common mistake to get wrong. Clear a tripped limit with sudo systemctl reset-failed myapp.service, then start it again.
Reloading without dropping requests
On deploy, you want new code without refusing connections. Gunicorn reloads gracefully when its master process receives SIGHUP: it re-reads configuration and replaces workers one by one. Tell systemd how to send that signal.
[Service]
ExecReload=/bin/kill -s HUP $MAINPIDThen run sudo systemctl reload myapp. Note that SIGHUP restarts the workers, which reimports your app code. It does not change the command line, so changes to ExecStart need daemon-reload followed by restart. A restart briefly interrupts service, while a reload does not.
Configuration and secrets
Keep secrets out of the unit file, which anyone on the server can read with systemctl cat. Use an environment file instead.
[Service]
EnvironmentFile=/etc/myapp/envsudo install -d -m 755 /etc/myapp
sudo install -m 600 -o root -g root /dev/null /etc/myapp/env
sudo nano /etc/myapp/envThe file contains lines such as DATABASE_URL=postgres://..., with no export and no quotes needed for simple values. systemd reads it as root before dropping privileges, so the service user does not need access to it.
Basic hardening
systemd offers sandboxing options that cost one line each:
[Service]
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
ProtectHome=trueNoNewPrivileges blocks privilege escalation through setuid binaries. PrivateTmp gives the service its own /tmp. ProtectSystem=full makes /usr, /boot, and /etc read-only for the service. ProtectHome hides /home.
Socket access from Nginx
Nginx must be able to open /run/gunicorn/app.sock. On Debian and Ubuntu, Nginx workers run as www-data, which matches the unit above, so access works. If you run Gunicorn as a different user, check the socket with ls -l /run/gunicorn/app.sock, then put both users in a shared group and give that group write access to the socket. A permission mismatch shows up as a 502 with connect() ... failed (13: Permission denied) in the Nginx error log.
Diagnosing failed starts
When status shows failed, read the message next to it.
| Symptom in status or journal | Likely cause |
|---|---|
| `status=203/EXEC` | `ExecStart` path is wrong or the file is not executable. |
| `status=217/USER` | The `User=` account does not exist. |
| `status=200/CHDIR` | `WorkingDirectory` does not exist or is not accessible to the user. |
| `ModuleNotFoundError` or `Failed to find attribute` | Wrong `app:application` name, or packages missing from the venv. |
| `Connection in use` or `Address already in use` | Another process holds the port or a stale socket exists. |
| Service restarts repeatedly | The app crashes on start. Read `journalctl`, not `status`. |
To reproduce an error by hand, run the same command as the same user:
sudo -u www-data /srv/myapp/venv/bin/gunicorn --bind 127.0.0.1:8001 app:applicationIf that works but systemd fails, compare the working directory, environment variables, and file permissions.
Exercise
A service with Restart=on-failure is running. You run sudo systemctl stop myapp. Will systemd restart it? Then you run sudo kill -9 on the Gunicorn master PID instead. What happens, and why?
Show answer
After systemctl stop, systemd does not restart it, because an explicit stop is never treated as a failure. After kill -9, the master dies from a fatal signal, which counts as a failure, so systemd waits RestartSec and starts the service again. You can confirm with systemctl status myapp showing a new PID.
Exercise
After editing ExecStart to use --workers 5, you run sudo systemctl reload myapp and ps still shows three workers. What went wrong and what should you run?
Show answer
reload only sends SIGHUP through ExecReload, and systemd keeps the old ExecStart until its unit files are reread. Run sudo systemctl daemon-reload so systemd sees the edit, then sudo systemctl restart myapp so the new command line takes effect.