Linux β€’ Web Apps & APIs

How to Create a Systemd Service for Python (FastAPI, Flask, Gunicorn, Uvicorn)

Deploying Python web APIs (FastAPI, Django, Flask) in production requires a WSGI/ASGI server like Gunicorn or Uvicorn managed by systemd. This service ensures workers restart if memory limits are exceeded or unhandled exceptions occur.

/etc/systemd/system/python-app.service
[Unit]
Description=FastAPI / Uvicorn Production Web Service
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/my-python-app
ExecStart=/var/www/my-python-app/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 4
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=python-app
Environment=PYTHONUNBUFFERED=1
EnvironmentFile=/var/www/my-python-app/.env

[Install]
WantedBy=multi-user.target
Customize:
User:
WorkingDir:
ExecStart:

Systemctl Lifecycle & Journalctl Monitoring

sudo systemctl daemon-reloadRegister new unit file with systemd
sudo systemctl enable --now python-appStart service now and enable on boot
sudo systemctl restart python-appRestart Python processes after a code git pull
sudo journalctl -u python-app -n 50 --no-pagerPrint last 50 log lines without entering pagination

Linux & Systemd Production Best Practices

  • Set `PYTHONUNBUFFERED=1` in the Environment block so print statements and logger outputs appear instantly in journalctl without buffer delay.
  • Always point `ExecStart` to the Python or Uvicorn binary inside your virtualenv (`/path/to/venv/bin/uvicorn`). Do not activate the virtualenv in bash.

Frequently Asked Questions About Python FastAPI/Flask Service

Frequently Asked Questions

Frequently Asked Questions

Everything you need to know regarding specifications, syntax, and security best practices.

The recommended formula is `(2 x $NUM_CORES) + 1`. On a 2-core VPS, 4 or 5 workers maximize CPU concurrency.