Skip to content

Instantly share code, notes, and snippets.

@dunkelstern
Created May 8, 2023 17:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dunkelstern/5bfe7414fc0b7e8a9f6e1c4c78fd2543 to your computer and use it in GitHub Desktop.
Save dunkelstern/5bfe7414fc0b7e8a9f6e1c4c78fd2543 to your computer and use it in GitHub Desktop.
Systemd Unit for running python application in virtualenv

Assumptions

  • Username is user
  • User is in group user
  • User's home is /home/user
  • Python application is in /home/user/pythonapp
  • Python script is named start.py
  • Virtual environment is /home/user/.virtualenvs/pythonapp created with python -m venv /home/user/.virtualenvs/pythonapp

You can add multiple Environment lines if you need more env-variables

How to use it

  • Usually systemd unit goes to /etc/systemd/system/pythonapp.service
  • Reload systemd after changing unit files: systemctl daemon-reload
  • Enable units by systemctl enable pythonapp
  • Start with systemctl start pythonapp
  • Stdout and Stderr will go to the system journal: journalctl -xeu pythonapp to view
[Unit]
Description=Sample Python Application
After=network.target
[Service]
type=exec
Environment=EXAMPLE_ENV=bla
WorkingDirectory=/home/user/pythonapp
ExecStart=/home/user/.virtualenvs/pythonapp/bin/python /home/user/pythonapp/start.py
Restart=always
User=user
Group=user
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment