Create a systemd service for Flask API(for GNU/Linux distros)

Hello… in this post, I want to show you something about a productivity trick in server side. I will talk about the systemd package on Linux systems, which will be used in the application development process or for custom.

First of all, systemd is a software package included in linux operating systems, according to Lennart Poettering… He is the author of the package software.

It is created by the init process and takes 1 as the process id (pid). systemd services are started automatically and can be managed by root users. With the sytemctl command, systemd services can be started (start) and stopped (stop), applications that have changed configuration files can be re-read and restarted (reload), the status of the process can be obtained (status), and its activation can be controlled after the system restarts ( enable/disable). For more information, see the manual page.

$ man systemctl

Flask microframework is a very easy-to-use framework software for creating simple APIs. To add it to your script file, it is sufficient to download the flask module with pip3 and include it on the page, and create an app object to create your routes. Then the script below can be used.

import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route('/', methods=['GET'])
def function_one():
return "<div style=\"   display: flex;justify-content: center;align-items: center;height: 100%;border: 3px solid green;  \" ><p>Hello sir, It seems to work properly.Here is<span style=\"font-size:50px; color:white; background-color:red\"> / </span></p> </div>"

@app.route('/users', methods=['GET'])
def function_two():
return "<div style=\"   display: flex;justify-content: center;align-items: center;height: 100%;border: 3px solid green;  \" ><p>Hello sir, It seems to work properly.Here is<span style=\"font-size:50px; color:white; background-color:green\"> /users</span> </p> </div>"

@app.route('/products', methods=['GET'])
def function_three():
return "<div style=\"   display: flex;justify-content: center;align-items: center;height: 100%;border: 3px solid green;  \" ><p>Hello sir, It seems to work properly.Here is<span style=\"font-size:50px; color:white; background-color:blue\"> /products </span></p> </div>"

app.run()

By default, it starts working on the localhost:5000 port. To change port or host, you can give new host and port with app.run(host='ip_addr',port='port' ).

After the script is saved as app.py, it can be converted to a systemd service by writing the systemd service.

When a flask application is run with python, it is raised on the "development server". There are different options for the API to be raised in the "Production" environment. You can learn from the Flask manual page.

Depending on the operating system, sudo vi /lib/systemd/system/myFlaskApp.service or Let's open it in nano editor. This path may differ depending on the distro. To find out where other services are, e.g. for mariadb service,

$ locate mariadb

If there is no output, use the updatedb command and try again. services can also be found under /usr/lib/systemd/system/… Or you can create such a directory under the /usr directory.

/lib/systemd/system/myFlaskApp.service =>

[Unit]
Description=My flask API service
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=your username
PermissionsStartOnly=true
ExecStart=/usr/bin/python3 /your/path/app.py
Restart=on-failure
TimeoutSec=600

Note: Here we set Restart=on-failure. This indicates that we only want it to restart when the exit code is not 0. We can also add Restart=always and RestartSec=1 lines instead. It makes it reboot in any case.
You can add a config file with sudo vi /etc/init/myFlaskApp.config.

description "MyFlaskApp"
start on stopped rc RUNLEVEL=[2345]
respawn
exec python3 /your/path/app.py

Then,

$ sudo systemctl start myFlaskApp

You can start the service with this command. Make sure it is in the active(running) state with systemctl status.

This method can be useful for developments made on the cloud service, but it is recommended to use the deployment options above in terms of both performance and manageability in the production environment.

This service runs in the background without user intervention. It takes a pid as can be seen with sytemctl status. If a modular API structure is created and the route operation and other operations are isolated from each other, this method may be useful in situations where no modifications to this file are required. In this way, we can call it “life hacking”. To use something as the meaning of the word to improve a lifestyle other than its purpose…

You can make processes like this or that don't need to be interfered with by your system as systemd service and control them with systemctl.

13