Howto setup a Python Flask application as a system service on Linux

With Flask you can have your backend coded in minutes, and with for example a Linode server you can get a $10/month-server up and running in no time.

But now that you have your Flask-application working, how do you automatically start it on your server?

If you have SYSTEMD (look it up!) you can easily create a system service, that you can start with the systemctl command.

In /etc/systemd/system you create a file, lets call it myservice.service

[Unit]
Description=My demo service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=<the user account you want to run it on>
ExecStart=/usr/bin/env bash /home/<your-home-dir>/myservice/start_server.sh

[Install]
WantedBy=multi-user.target

The content of the start_server.sh should be as rudimentary as possible, making sure that the app is started in the right place, with the right parameters/config.

# /home/<user>/start_service.sh
# Make sure we are, where we are supposed to be!
cd /home/<your-home-dir>/myservice
python3 app.py

This example assumes that Python3 is installed and working, and that all dependencies are met.

Now you can control your service with:

sudo systemctl status myservice
sudo systemctl start myservice
sudo systemctl enable myservice # make it auto-start at boot

To remove the service

sudo systemctl stop myservice
sudo systemctl disable myservice
sudo rm /etc/systemd/system/myservice.service

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.