Linux 与服务器运维 / 系统课时

编写应用的 Service Unit

编写应用的 Service Unit

把一个长期运行的后台程序交给 systemd 托管,关键不是“能启动”而是把运行身份、工作目录、启动命令和失败后的行为写清楚。本节用一个最小后台进程完成完整 Service Unit,并通过 systemd 自带工具验证配置与运行状态。

学习目标

  • 能用 ExecStart、User、Group、WorkingDirectory 描述服务的运行上下文
  • 能安装、加载并启动一个自定义 .service 单元
  • 能用 systemd-analyze、systemctl 和 journalctl 验证服务是否按预期运行

准备应用和运行账号

不要让普通业务进程默认以 root 身份运行。下面创建专用系统账号和一个前台常驻脚本。脚本必须保持在前台,systemd 才能直接跟踪主进程。

bash
getent group hello-worker >/dev/null || sudo groupadd --system hello-worker
id -u hello-worker >/dev/null 2>&1 || sudo useradd --system --gid hello-worker --home-dir /var/lib/hello-worker --create-home --shell /usr/sbin/nologin hello-worker

sudo install -d -o root -g root -m 0755 /opt/hello-worker/bin
sudo tee /opt/hello-worker/bin/worker.sh >/dev/null <<'EOF'
#!/bin/sh
set -eu

echo "worker-alive pid=$$"
while :; do
  sleep 30
done
EOF
sudo chmod 0755 /opt/hello-worker/bin/worker.sh

echo "prepared"

预期输出:

text
prepared

账号创建工具在部分发行版上可能额外打印提示信息,但成功执行时最后会看到 prepared。如果系统的 nologin 位于其他路径,可先用 command -v nologin 确认后调整 useradd --shell。

写出 Service Unit

将下面内容保存为 /etc/systemd/system/hello-worker.service。ExecStart 使用绝对路径,WorkingDirectory 指定进程启动后的当前目录,而不是用来替代可执行文件路径。

ini
[Unit]
Description=Hello Worker demo service

[Service]
Type=simple
User=hello-worker
Group=hello-worker
WorkingDirectory=/opt/hello-worker
ExecStart=/opt/hello-worker/bin/worker.sh
Restart=on-failure
RestartSec=3s

[Install]
WantedBy=multi-user.target

这里最值得检查的是四个字段:User 和 Group 决定进程权限;WorkingDirectory 必须真实存在且对运行用户可进入;ExecStart 是 systemd 实际执行的命令;Restart=on-failure 用于失败后的自动恢复,正常执行 systemctl stop 不会因此触发持续重启。

如果先在当前目录保存为 hello-worker.service,可执行:

bash
sudo install -o root -g root -m 0644 ./hello-worker.service /etc/systemd/system/hello-worker.service
echo "unit-installed"

预期输出:

text
unit-installed

加载并启动服务

修改或新增 Unit 文件后先让管理器重新读取配置,再启用并立即启动服务。enable 建立开机启动关系,--now 则让本次启动同时发生。

bash
set -e
sudo systemd-analyze verify /etc/systemd/system/hello-worker.service
echo "verify=ok"
sudo systemctl daemon-reload
sudo systemctl enable --now hello-worker.service >/dev/null 2>&1

echo "state=$(systemctl is-active hello-worker.service)"
echo "enabled=$(systemctl is-enabled hello-worker.service)"

预期输出:

text
verify=ok
state=active
enabled=enabled

systemd-analyze verify 成功时通常没有诊断信息;这里通过 set -e 保证验证失败后不会继续启动服务。若它报告未知指令、路径错误或语法问题,应先修复 Unit,再执行 daemon-reload。

验证运行日志

服务显示为 active 只说明 systemd 认为主进程仍在运行,还应确认真正执行的是目标脚本。读取应用写入标准输出并由 journal 收集的日志即可完成验证。

bash
sudo journalctl -u hello-worker.service -o cat | grep '^worker-alive' | tail -n 1

预期输出:

text
worker-alive pid=<ID>

其中 <ID> 是本次启动的实际进程 ID,每次重启都可能不同。若没有这行日志,依次检查 systemctl status hello-worker.service、脚本是否可执行、WorkingDirectory 是否存在,以及 User、Group 是否有权限访问路径中的各级目录。

这个 Unit 已具备后台服务最小而完整的托管条件:systemd 知道以谁的身份、从哪个目录、执行什么命令,以及进程异常结束后该如何处理。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

编写应用的 Service Unit

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通