Creating a systemd service for a Flask application

Christos Falas
2 min readJan 11, 2020

Systemd allows for files to be run as services, meaning that they are automatically started on startup, and more generally managed by systemd, including logs, restart on errors, and support for many features.

So, let’s make a server! For this, I will use a Flask application (this app shows the NASA Astronomy Picture of the Day for a selected date). My code for the app is multiple files, but to run the server, I run python app.py from the project root directory. In order to make the service file for this server, we need to create a new file inside /etc/systemd/system/ that ends with .service. Let’s call it flask-server.service. The contents will be the following (I will explain each line in a bit):

[Unit]
Description=NASA APOD API Server
After=network.target
[Service]
Type=simple
ExecStart=/home/cfalas/Documents/Coding/nasa_apod/env/bin/python /home/cfalas/Documents/Coding/nasa_apod/app.py
Restart=always
[Install]
WantedBy=multi-user.target

Next, in order to load the service and start it, run

sudo systemctl start flask-server
sudo systemctl enable flask-server

Now, let me (try to) explain what each line does:

Firstly, the first line (and all lines that start/end with []) show a section

The second line contains a description of what the service does

After shows the requirements that this service has. Since it’s a server, it needs to be working with the network, and can’t start before the network service does. This line makes sure that it won’t.

Moving on the next section, we get into the details of the service. The Type of the service, in this case, is simple, since the whole service is one file. You can see all of the types if you run man systemd.service. Next, ExecStart shows the command to run in order to start the service. In my case, this is the full path of python app.py. I made sure to choose the correct python binary which is in the virtual environment that has all of the dependencies that my app needs.

Next, Restart is there so that the server restarts when there is an error

Finally, WantedBy shows the way that the service will be enabled. In this case, this means that it will be enabled during a phase where the network is working, but the GUI is not ready yet.

That’s it for a very simple systemd service. Of course, there are many features that I haven’t used, but are out there!

--

--