Skip to content

通过systemd实现linux后台自启动web服务 #11

@MobiusT

Description

@MobiusT

个人用途

配合nonebot-plugin-memes-api插件实现多环境(bot)共用同一个meme-generator,省去重复维护工作

准备工作

以下是我的环境

  • 操作系统 CentOS7.9 (其他系统应该也行)
  • systemd, 检查命令:
whereis systemd 

meme-generator, 检查命令:

meme -h
  • meme-generator, 为了及时更新表情,改用git clone安装meme-generator,安装命令:
cd /app/mobius/webapps # 以此地址为例,可以自行更改
git clone https://github.com/MeetWq/meme-generator
  • root权限

操作步骤

  1. 配置meme-generator,将web监听地址变更为0.0.0.0,可通过局域网内访问交互式 API 文档(访问 http://ip:port/docs )检查
[server]
host = "0.0.0.0"  # web server 监听地址
port = 2233  # web server 端口
  1. 确认meme命令绝对路径
which meme  # ~/.local/bin/meme  为例 ,熟悉linux的朋友此时应该已经知道绝对路径了
cd ~/.local/bin/ 
pwd   # /app/mobius/.local/bin  为下文示例
  1. python命令绝对路径
python  -V  # 检查版本,旧版本linux不要使用到python2.7去了
which python  # /usr/bin/python3  # 为下文示例 
  1. root权限新建service文件,非root用户自行添加sudo
[Unit]
Description=meme Service     
After=network.target

[Service]
User=mobius
Group=root
Type=simple
ExecStart=/usr/bin/python3 -m meme_generator.app
WorkingDirectory=/app/mobius/webapps/meme-generator
Restart=on-failure

[Install]
WantedBy=multi-user.target

以下为旧版

ExecStart=/app/mobius/.local/bin/meme start
WorkingDirectory=/
  • Description 服务的描述
  • After 在network服务之后启动服务
  • User&Group 启动服务使用的用户和组,可不用
  • Type=simple,默认值,执行ExecStart指定的命令,启动主进程
  • ExecStart 启动当前服务的命令,务必使用第二点中获取到的绝对路径
  • WorkingDirectory 工作路径,使用准备工作中git clone 的位置
  • Restart=on-failure 定义何种情况 Systemd 会自动重启当前服务
  • WantedBy,值是一个或多个Target,当前Unit激活时(enable)符号链接会放入/etc/systemd/system目录下面以Target名+.wants后缀构成的子目录中
vi /usr/lib/systemd/system/meme.service  # 将上文内容写入到此文件中,:wq保存
systemctl enable meme.service # 开机启动
systemctl start meme.service # 启动服务
systemctl stop meme.service # 停止服务
tail -100f /var/log/messages|grep meme  # 查看日志

更新表情

  1. 更新meme-generator:
cd /app/mobius/webapps/meme-generator # 以此地址为例,应使用clone位置
git pull
  1. 重启meme:
systemctl restart meme.service # 重启服务
  1. 使用api的更新表情命令

其他

本issue为个人学习探索的总结记录,如有错误欢迎各位大佬指正

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions