春江暮客

春江暮客的个人学习分享网站

centos7手动创建自定义系统服务

2019-11-17 技术
centos7手动创建自定义系统服务

在linux系统开发过程中,有时自己的程序可能会出问题或者被关掉,如果要一直维持运行的话,把程序加入到服务列表中是非常好的一个做法,这里就说明讲linux中讲自有程序加入到系统服务的过程,以centos7为例。

步骤:

  1. python的flask自建一个简单的web程序
  2. 加入到系统服务
  3. 启动服务以及详细参数说明

python的flask自建一个简单的web程序

这一步可以是任何你自己想要加入系统服务的程序,这里的例子是flask的一个web程序,只会输出hello world

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

不要把长期运行的服务程序直接放在 /root 下面,再交给普通用户运行。更稳妥的做法是把程序放到一个服务用户可访问的目录,比如 /opt/flask_app。

mkdir -p /opt/flask_app
cd /opt/flask_app

然后建立一个简单的 flask 程序:

## 位置 /opt/flask_app/hello.py
from flask import Flask
app = Flask(__name__)

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

测试运行


export FLASK_APP=hello.py
flask run

可以看到成功运行 flask_app wget 测试 wget_test

加入到系统服务

到system服务目录创建文件,比如叫flask_app

touch /etc/systemd/system/flask_app.service

内容写入

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

[Service]
Type=simple
Restart=always
RestartSec=1
User=www
WorkingDirectory=/opt/flask_app
Environment=FLASK_APP=hello.py
ExecStart=/usr/local/bin/flask run --host=0.0.0.0 --port=5000

[Install]
WantedBy=multi-user.target

这里 WorkingDirectory 和 Environment 由 systemd 直接提供,比额外写一个 /root/hello.sh 脚本更直接,也更容易排查问题。

启动服务以及详细参数说明

启动服务

systemctl daemon-reload
systemctl start flask_app
systemctl enable flask_app
systemctl status flask_app
  • Description:系统服务描述
  • After:紧接程序后面运行,这里连接网络后运行
  • StartLimitIntervalSec:systemd 计算启动频率限制的时间窗口
  • Restart:中断是否重启
  • RestartSec:中断后重启等待时间
  • User:指定程序运行用户
  • WorkingDirectory:程序运行目录
  • Environment:传给程序的环境变量
  • ExecStart:系统服务程序运行的命令,需要完整目录

install项目照抄就行。。。

总结:

本文解决一个常见的问题,就是遇到需要将自己的程序作为系统服务的时候,怎么添加 systemd 服务,以及实现程序被中断后自动重启,达到程序可以稳定后台运行的目的。实际配置时,尽量避免把服务文件和程序放在 /root 目录再交给普通用户运行。

标签

1024 12306 ablang adsense agents.md ai ai-agent ai-agents ai-seo algorithm amp antibodies apparmor argparse automation backup bash batch-processing binarycif bioinformatics biopython blockchain boltz bootstrapping boxes bubblewrap c-index cca cdn chatgpt checkpoint cli cloudflare codex cofoldarena concurrency configuration copy cpu监控 cron csv cuda curl data-leakage data-processing data-quality data-validation datascience datavisualization datetime debugging decimal deployment desktop-app devtools disk-space disown dns docker dovecot download electron encoding esm esm2 esm3 esmc esmfold2 faceswap fasta fastmcp faulthandler ffmpeg file-descriptors file-io flashppi flask folium frontend game generator git github-actions google google-research grep gzip harness hls html http hugo imports indexnow javascript jev json jsonl just k-means kaggle langfuse leecode linux list litellm llm llms.txt logging logs lollipop lsof m3u8 machine-learning macos manacher matplotlib mcp memory mirror mmcif model-evaluation monitoring mp3 mp4 mpnn multiomics mutation mysql nanobert nanobodies networkx nginx normalize numpy ollama omegatherm pandas password pathlib pdb pep-723 phaser pillow pip postfix preprocessing print protein-alignment protein-design protein-embeddings protein-interactions protein-language-models protein-stability protein-structure proxy pydantic pyecharts pyqt python python3 r raincloud reproducibility requests reservoir-sampling rfoptimization rg ripgrep rosettafold3 roundcube rrsi rsi rsync s-tui sampling scale scikit-learn scrapy screen seaborn security selenium seo sequence-identity sha256 shell signals sklearn socket solana somaticsignatures spl sqlite ssh standardize static-site subprocess symlink sysadmin system-one tarfile tcp tensorflow tkinter tls toml tracemalloc tron tronpy troubleshooting turtle typesafe-ai ubuntu unicode urllib usdt utf-8 uv vhhbert vite webp wordcloud wordpress workflow yaml zipfile zoneinfo 后台 寓言 概率 经济 贸易 迅雷解析 钱包

友情链接

其它