Create a simple systemd service unit file for uvicorn

1 minute read

For some reason I had to run simple FastAPI app at startup with systemd without guvicorn or Nginx as reverse proxy. To do that I created pytohn venv and very simple systemd service unit file. I think there is a space to improve that but it was the easiet way to publish myapp on some production server. But we have to remember that isn’t a goog practise.

1sudo vim /usr/lib/systemd/system/tbqueuewatch.service

Paste this code:

 1[Unit]
 2Description=myapp
 3After=network.target auditd.service
 4Wants=
 5
 6[Service]
 7ExecStart=/opt/python39/bin/uvicorn app.main:app --reload --host 0.0.0.0 --port 5000
 8ExecReload=
 9WorkingDirectory=/opt/myapp
10Restart=on-failure
11PrivateTmp=true
12ProtectSystem=full
13User=user
14Group=group
15
16[Install]
17WantedBy=multi-user.target

Reload systemd to ensure it detects the new service:

1sudo systemctl daemon-reload

Start the service:

1sudo systemctl start myapp

Enable the service to start automatically at boot time:

1sudo systemctl enable myapp