Sub topic 3
Keeping the app running with systemd
This chapter assumes you have Gunicorn serving app:application on a Unix socket at /run/gunicorn/app.sock, Nginx proxying to it, and sudo access on a Debian or Ubuntu server.
Keeping the app running with systemd
systemd is the service manager that starts programs at boot and restarts them after a crash. Save this unit as /etc/systemd/system/gunicorn.service:
[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.targetLoad the unit, then start it at boot and right now:
sudo systemctl daemon-reload
sudo systemctl enable --now gunicorn
systemctl status gunicornPassing Host, client IP, and scheme to the app
Gunicorn sees Nginx as the client, so Nginx must pass the original details in headers. Add these lines to the location / block:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;Terminating HTTPS at the web server
Nginx can handle TLS, so the app receives plain HTTP. Add listen 443 ssl; with your ssl_certificate and ssl_certificate_key paths to the server block. The app reads X-Forwarded-Proto to know the visitor used HTTPS.
> Only trust forwarded headers when Nginx is the only path to the app. Bind Gunicorn to the socket, not a public port.
Service users, file permissions, and blocking hidden files
The service runs as www-data, so it should read code but not change it. Give the deploy user ownership and the service group read access:
sudo chown -R deploy:www-data /srv/myapp
sudo chmod -R u=rwX,g=rX,o= /srv/myappDeny hidden files such as .env and .git in Nginx:
location ~ /\.(?!well-known) {
deny all;
}Reading logs and fixing 502, 403, and 404 errors
| Status | Usual cause | First check |
|---|---|---|
| 502 | Gunicorn is stopped or the socket path is wrong | `systemctl status gunicorn` |
| 403 | Nginx cannot read files, or a deny rule matches | `sudo tail -n 20 /var/log/nginx/error.log` |
| 404 | Wrong `root` or `alias` path | Confirm the file exists under that path |
Read the app's own log with journalctl -u gunicorn -n 50.
Choosing worker counts and basic tuning
A common starting point is two workers per CPU core, plus one. Each worker uses memory, so check free -m before raising --workers.
Exercise:
Exercise
Gunicorn is running, but every request returns 502. Name the two commands you would run first, and what each one tells you.
Show answer
Run systemctl status gunicorn to confirm the service is active, and sudo tail -n 20 /var/log/nginx/error.log to see whether Nginx reports a missing or refused socket. A stopped service or a wrong socket path causes the 502.