Philipp's Computing Blog

Success is about speed and efficiency

Start a Python Tool or Web App that uses Virtualenv on system startup using Systemd

I.e. deploying a tool or Python app using systemd.

I would recommend setting up the environment variables as well as activating the virtualenv in a Bash script and call that from systemd.

Working setup

Here is the bash script starting the bottle.py web app after setting up the virtualenv. It's stored in /home/coltrims/MaxiGauge/webserver.sh:

#!/bin/bash

HOME=/home/coltrims
VENVDIR=$HOME/.virtualenvs/hhg
BINDIR=$HOME/MaxiGauge

cd $BINDIR
source $VENVDIR/bin/activate
$BINDIR/webserver.py

And here is the systemd configuration file /etc/systemd/system/bottle-web-app.service:

[Unit]
Description=Bottle Web App MaxiGauge
After=network.target

[Service]
Type=simple
User=coltrims
Group=users
ExecStart=/home/coltrims/MaxiGauge/webserver.sh

[Install]
WantedBy=multi-user.target

After creating the systemd .service file do:

systemctl daemon-reload
systemctl status bottle-web-app.service
systemctl restart bottle-web-app.service
#Enable it to be started on bootup:
systemctl enable bottle-web-app.service

NOT-WORKING-YET

I was trying to get rid of the Bash script and integrate it all into the systemd .service file but this does not work yet!!!:

### This systemd .system config file DOES NOT WORK
[Unit]
Description=Bottle Web App MaxiGauge
After=network.target

[Service]
Type=simple
User=coltrims
Group=users
Environment="VENVDIR=/home/coltrims/.virtualenvs/hhg" "BINDIR=/home/coltrims/MaxiGauge"
ExecStart=bash -c"cd $BINDIR; source $VENVDIR/bin/activate; $BINDIR/webserver.py"

# Give a reasonable amount of time for the server to start up/shut down
TimeoutSec=20

[Install]
WantedBy=multi-user.target

All that systemd tells me is the following:

bottle-web-app.service lacks ExecStart setting. Refusing.

If you know how to resolve this or what the problem is, please let me know.

Resources