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.targetCustomize:
User:
WorkingDir:
ExecStart:
Systemctl Lifecycle & Journalctl Monitoring
sudo systemctl daemon-reloadRegister new unit file with systemdsudo systemctl enable --now python-appStart service now and enable on bootsudo systemctl restart python-appRestart Python processes after a code git pullsudo journalctl -u python-app -n 50 --no-pagerPrint last 50 log lines without entering paginationLinux & 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.
Related Linux & Systemd Services
View All ServicesWeb Apps & APIs
How to Create a Systemd Service for Node.js (Express, NestJS, Next.js)
node-app.serviceGuide β
Web Apps & APIs
How to Create a Systemd Service for Go (Golang) Compiled Binary
go-service.serviceGuide β
Background Workers & Daemons
How to Run Background Workers (Celery, BullMQ, Sidekiq) with Systemd
queue-worker.serviceGuide β
Timers & Automation
How to Create a Systemd Timer to Replace Cron Jobs
backup-task.serviceGuide β
Infrastructure & Tunnels
How to Run Docker Compose as a Systemd Service
docker-compose-app.serviceGuide β
Infrastructure & Tunnels
How to Keep Reverse SSH Tunnel Persistent with Autossh & Systemd
reverse-tunnel.serviceGuide β