First, let's make ourselves a simple python web server with flask:
from flask import Flask
app = Flask(__name__)
import os
PORT = int(os.getenv('FLASK_PORT', 5000))
@app.route('/')
def hello_world():
return 'Hello, PuPPy!'
if __name__ == '__main__':
app.run(port=PORT)Cool! Let's try running it:
$ python3 main.pyUnsurprising. But, what if we wanted to make sure that this was always running, and was started as soon as the computer turned on? systemd to the rescue!
Let's create a service file at systemdflaskdemo.service:
[Unit]
Description=A baby fask app
[Service]
ExecStart=/usr/bin/python3 /home/stuart/code/systemd-talk/main.py
Environment=FLASK_PORT=8050
Restart=always
[Install]
WantedBy=default.target
This service config file tells systemd when and how to run our process - in this case a web server. After creating this config file, we tell systemd to enable this service for our user:
$ systemctl --user enable $(pwd)/systemdflaskdemo.serviceCool! But it's not running yet, as we can see when checking the status of the service:
$ systemctl --user status systemdflaskdemo.serviceSimple enough to fix, let's just start it:
$ systemctl --user start systemdflaskdemo.serviceThat WantedBy=default.target tells systemd that we want the process to start as soon as the user logs in, so we should be covered in the case of a system restart also, if we enable lingering for the current user:
$ loginctl enable-linger $(whoami)If you ever want to stop the service, that's also easy:
$ systemctl --user stop systemdflaskdemo.serviceAnd, say you want to totally remove the service? Just disable it!
$ systemctl --user disable systemdflaskdemo.serviceIn my experience, daemon-reload hasn't always worked for reloading --user service configs, but I am still but a systemd noob. Hope this has helped!