Manually Create Custom System Service on CentOS7
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:
- Build a simple Flask web program with Python
- Add it to system services
- 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.
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/en/457.html
- 版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。