首页/系统/信创系统运维速查/编写自定义 systemd 服务单元
服务与运维65 条

编写自定义 systemd 服务单元

把自研程序注册成受管服务:在 /etc/systemd/system 写 .service 文件,声明 ExecStart、Restart 与安装段,daemon-reload 后 enable --now 纳入开机与守护管理。

信创系统运维速查系统更新于 2026-10-12

示例 /etc/systemd/system/myapp.service

示例 /etc/systemd/system/myapp.service
[Unit]
Description=MyApp Service
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/myapp -c /etc/myapp/app.conf
Restart=on-failure
RestartSec=5
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target

上线流程

上线流程
systemctl daemon-reload
systemctl enable --now myapp.service
systemctl status myapp.service --no-pager -l
ExecStart 必须写绝对路径;老式脚本自行后台化的程序用 Type=forking 并配 PIDFile,前台进程用 Type=simple。

易错点

  • 改完单元文件必须 systemctl daemon-reload 才生效,只 restart 不会读取新内容
  • User/WorkingDirectory/日志路径要提前建好并给对权限,否则首次启动直接失败(status=200/203 类错误)

数据来源与参考

  • man 5 systemd.service
  • openEuler 文档:编写 systemd 单元文件
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌