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

把普通程序交给 systemd 运行

把普通程序交给 systemd 运行

一个能在终端里正常运行的程序,要成为可靠的后台服务,还需要让 systemd 知道“启动什么、从哪里启动、如何判断状态,以及是否随系统启动”。本篇用一个最小脚本完成从 Unit 创建到启动、自启和日志验证的完整托管流程。

学习目标

  • 能为普通可执行程序编写最小可用的 .service Unit
  • 能完成 daemon-reload、start、enable 并区分它们的作用
  • 能用 status 与 journalctl 验证服务是否真正由 systemd 托管

准备一个可持续运行的程序

systemd 最适合直接托管前台运行、不会自行 fork 到后台的进程。先创建一个每 5 秒输出一条日志的脚本,模拟普通长期运行程序。

bash
sudo tee /usr/local/bin/hello-service.sh >/dev/null <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

while true; do
  printf 'hello from systemd at %s\n' "$(date --iso-8601=seconds)"
  sleep 5
done
EOF

sudo chmod 0755 /usr/local/bin/hello-service.sh
test -x /usr/local/bin/hello-service.sh && echo "executable ready"

预期输出

text
executable ready

这里故意让脚本保持前台运行。对默认的 Type=simple 来说,ExecStart 启动的主进程就是 systemd 直接跟踪的服务进程,不需要程序自己写 PID 文件或转入后台。

创建 Service Unit

系统级自定义 Unit 通常放在 /etc/systemd/system/。创建 /etc/systemd/system/hello-service.service:

ini
[Unit]
Description=Minimal hello service

[Service]
Type=simple
ExecStart=/usr/local/bin/hello-service.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

ExecStart 必须指向 systemd 能直接执行的命令。这里使用绝对路径,避免依赖交互式 Shell 的当前目录、别名或用户环境。Restart=on-failure 表示进程异常退出时尝试重启,但正常停止服务时不会因为这个设置立即拉起。

创建或修改 Unit 后,先验证语法,再让 manager 重新读取配置:

bash
sudo systemd-analyze verify /etc/systemd/system/hello-service.service
sudo systemctl daemon-reload
echo "unit reloaded"

预期输出

text
unit reloaded

systemd-analyze verify 在配置无明显错误时通常不输出内容;如果 Unit 中存在未知指令、依赖问题或路径错误,会直接给出诊断。daemon-reload 只重新读取 Unit 文件,不会自动启动或重启服务。

启动并检查运行状态

现在让 systemd 启动服务,再读取状态和最近日志:

bash
sudo systemctl start hello-service.service
systemctl is-active hello-service.service
systemctl show hello-service.service -p MainPID --value
sudo journalctl -u hello-service.service -n 3 --no-pager

预期输出

text
active
<ID>
<TIME> <HOST> hello-service.sh[<ID>]: hello from systemd at <TIME>
<TIME> <HOST> hello-service.sh[<ID>]: hello from systemd at <TIME>
<TIME> <HOST> hello-service.sh[<ID>]: hello from systemd at <TIME>

其中 <ID>、<TIME>、<HOST> 会随机器和运行时刻变化。脚本写到标准输出的内容会被 journald 收集,因此不需要额外指定日志文件就能通过 journalctl -u 查看。

设置开机自动启动

start 只影响当前运行状态;enable 负责建立启动依赖,使服务在匹配的 target 启动时被拉起。执行:

bash
sudo systemctl enable hello-service.service
systemctl is-enabled hello-service.service

预期输出

text
enabled

在常见发行版中,enable 还会显示创建符号链接的信息,具体路径可能不同,因此验收时以 systemctl is-enabled 返回 enabled 为准。

识别四个动作的边界

完成一次自定义服务托管时,最容易混淆的是配置刷新、运行状态和开机策略:

动作 主要作用 是否立即启动服务
daemon-reload 重新读取 Unit 文件 否
start 启动当前服务实例 是
restart 停止后重新启动,应用新的运行配置 是
enable 配置后续开机启动关系 否

以后修改 /etc/systemd/system/hello-service.service 时,先执行 daemon-reload,再根据是否需要让新配置立即生效选择 restart。只改 Unit 文件而不 reload,systemd manager 仍可能继续使用旧配置;只 enable 而不 start,当前会话中服务也不会因此立刻运行。

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

目录与阅读设置

阅读设置

17

记录一个想法

把普通程序交给 systemd 运行

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

登录哪都通