BOBOBK

Manually Create Custom System Service on CentOS7

TECHNOLOGY

During Linux system development, sometimes your program might crash or be stopped. To keep it running continuously, adding the program to the service list is a very good practice. Here is an explanation of how to add your own program to system services in Linux, taking CentOS7 as an example.

Steps:

  1. Build a simple Flask web program with Python
  2. Add it to system services
  3. Start the service and detailed explanation of parameters

Build a simple Flask web program with Python

This step can be any program you want to add to system services. The example here is a simple Flask web app that only outputs “Hello, World!”

yum install python-pip -y  
pip install --upgrade pip  
pip install flask  

Create a simple Flask program under root user directory, first:

## Location /root/hello.py  
from flask import Flask  
app = Flask(__name__)  

@app.route('/')  
def hello_world():  
    return 'Hello, World!'  

Test run:

export FLASK_APP=hello.py  
flask run  

You should see it running successfully:

Test with wget:

Add to system services

First, write a script to run the hello program. Flask needs environment variables so it’s a bit more complicated, others are easier. The script hello.sh is as follows:

cd /root  
export FLASK_APP=hello.py  
flask run  

Create a systemd service file, for example named flask_app:

touch /etc/systemd/system/flask_app.service  

Write the following content into it:

[Unit]  
Description=flask_app service  
After=network.target  
StartLimitIntervalSec=0  

[Service]  
Type=simple  
Restart=always  
RestartSec=1  
User=www  
ExecStart=/usr/bin/bash /root/hello.sh  

[Install]  
WantedBy=multi-user.target  

Start service and explanation of parameters

Start the service:

systemctl start flask_app  
## or service flask_app start  
  • Description: system service description
  • After: runs after specified target, here after network is up
  • StartLimitIntervalSec: time interval for restart limit, here runs once network is up
  • Restart: whether to restart after stopping
  • RestartSec: wait time before restarting after stopping
  • User: specify which user runs the program
  • ExecStart: the command to run the service program, full path required

Just copy the install section as is…

Summary:

This article solves a common problem: how to add your own program as a system service, and how to achieve automatic restart when the program stops, to ensure the program runs stably in the background.

Related