如何把某个应用包装成服务aka后台运行

-目录-

将某个应用包装成服务(后台运行)

简要说明

在指定目录下创建服务说明文件

vim /etc/systemd/system/myapp.service

输入相关信息

[Unit]
Description=My Application
After=network.target

[Service]
User=yourusername
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/run.sh
Restart=always

[Install]
WantedBy=multi-user.target

保存配置

systemctl daemon-reload

启动服务和检查状态

systemctl start myapp.service && systemctl status myapp.service

设置开机自启动【可选】

systemctl enable myapp.service
systemctl disable my_service #关闭自启动

如有出错可检查详细日志文件

tail /var/log/syslog
tail /var/log/messages

详细说明

  1. .service文件可选择在以下目录创建
  1. [service]下的User 可以接受一个用户名或用户ID(UID)或用户组名或用户组ID (GID)作为参数,以标识服务所运行的用户和组。如果未指定,则默认情况下服务将以 root 用户身份运行。

  2. [service]下的WorkingDirectory,如果没有正确地设置 WorkingDirectory ,那么服务可能无法正常启动或运行,因为服务可能会试图在不正确的目录中寻找需要的文件或资源。在服务文件的配置中, WorkingDirectory 可以使用相对路径或绝对路径指定服务的工作目录。如果该选项未设置,则默认情况下服务将在 / 根目录下运行。

  3. [service]下的Restart,当 Restart=always 选项设置在服务文件中时,如果系统检测到服务已经停止(无论是由于任何原因),systemd 将自动尝试重新启动该服务。它将一直尝试重新启动服务,直到服务成功启动为止。

    除了 always,Restart 选项还支持其他几个值:

    • no:服务退出时不会重启。
    • on-abnormal:仅当服务以非正常方式退出时才会重启。
    • on-failure:仅当服务以错误状态(退出代码非零)退出时才会重启。
    • on-success:仅当服务以成功状态(退出代码为零)退出时才会重启。
    • on-watchdog:仅当服务未及时响应守护程序时才会重启。这个选项需要服务内部有守护程序的支持。
© 2019 - 2023 · YuYoung's Blog