Python / Uvicorn Fundamentals Interview Questions
How do you run Uvicorn with systemd for automatic restarts and log rotation?
On Linux servers without Docker, systemd is the standard way to run Uvicorn as a managed service - providing automatic restarts on failure, boot-time startup, and journal-based logging.
# /etc/systemd/system/myapp.service [Unit] Description=My FastAPI Application After=network.target [Service] Type=simple User=www-data Group=www-data WorkingDirectory=/var/www/myapp Environment="PATH=/var/www/myapp/.venv/bin" EnvironmentFile=/var/www/myapp/.env ExecStart=/var/www/myapp/.venv/bin/uvicorn main:app \ --host 127.0.0.1 \ --port 8000 \ --workers 4 \ --loop uvloop \ --log-level warning Restart=always RestartSec=5 [Install] WantedBy=multi-user.target
# Enable and start the service sudo systemctl daemon-reload sudo systemctl enable myapp sudo systemctl start myapp # Check status and logs sudo systemctl status myapp journalctl -u myapp -f # follow live logs journalctl -u myapp --since "1 hour ago" # Reload after config change sudo systemctl restart myapp # Graceful restart (sends SIGTERM then restarts) sudo systemctl reload-or-restart myapp # Socket activation (advanced - systemd creates the socket) # myapp.socket + myapp.service - Uvicorn started only when first connection arrives uvicorn main:app --fd 0 # fd 0 passed by systemd socket activation
Bind Uvicorn to 127.0.0.1 (loopback) in systemd deployments and use Nginx or Caddy as the front-facing reverse proxy. This keeps Uvicorn off the public network and lets the proxy handle SSL, rate limiting, and static files.
More Related questions...