Linux系统服务管理systemd:从零创建自定义服务
Linux系统服务管理systemd:从零创建自定义服务
快速了解 systemd 是什么
systemd 是当前大多数 Linux 发行版(如 CentOS 7/8、Ubuntu 16.04+、Debian 8+)默认的服务管理器。
它的核心作用是把后台程序(如 Nginx、MySQL)包装成 服务单元,让你用统一的命令来控制启动、停止、重启、查看状态和设置开机自启。
对于运维新手,学会 systemd 就能摆脱手动管理进程的混乱,提升效率。
从零创建一个自定义服务
假设你有一个简单的 Python 脚本 hello.py,希望它在开机后自动运行并在后台保持存活。
下面分步完成。
1. 确认你的系统使用 systemd
执行以下命令,看输出是否为 systemd:
ps --no-headers -o comm 1
如果返回 systemd,直接进入下一步。
2. 编写服务单元文件
服务单元文件存放在 /etc/systemd/system/ 目录下(系统服务)或 /usr/lib/systemd/system/(软件包自带)。
自定义服务建议放在前者。
创建文件 /etc/systemd/system/hello.service:
[Unit]
Description=Hello World Service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /home/user/hello.py
Restart=always
User=nobody
Group=nogroup
[Install]
WantedBy=multi-user.target
参数说明:
After=network.target:等网络就绪后再启动。ExecStart:服务启动时执行的命令,需写绝对路径。Restart=always:进程意外退出后自动重启。User/Group:以低权限用户运行,提升安全性。WantedBy:表示在 multi-user 模式(普通多用户模式)下应被启动。
3. 重新加载并启动服务
创建单元文件后,让 systemd 重新读取配置:
sudo systemctl daemon-reload
然后启动服务:
sudo systemctl start hello
如果需要开机自启:
sudo systemctl enable hello
避坑和高频报错
❌ 服务启动失败,没有错误信息
用以下命令查看详细日志:
journalctl -u hello.service --no-pager -n 50
常见原因:
- 脚本缺少可执行权限:确保脚本本身有
+x权限,或在ExecStart中明确指定解释器。 - 路径错误:
ExecStart要使用绝对路径。 - 依赖问题:脚本中需要网络或文件系统,但
After未设置相应依赖。
❌ enable 后下次重启服务未启动
检查服务是否被其他目标屏蔽,或查看 WantedBy 是否写错。
更稳妥的做法是:
sudo systemctl enable --now hello
--now 参数会同时启动并设置为开机自启。
❌ 服务一旦停止就自动重启太多
如果 Restart=always 且启动失败,会陷入无限重启。
调试时可以暂时改为 Restart=on-failure。
验证服务是否正常运行
- 查看服务状态:
sudo systemctl status hello
输出应显示 active (running)。
- 检查是否开机自启:
sudo systemctl is-enabled hello
输出 enabled 即正确。
- 手动停止和启动测试:
sudo systemctl stop hello
sudo systemctl start hello
确保两次操作都成功,且 status 显示预期状态。
如果你正在管理 Linux 系统服务,建议先按本文步骤亲手试一遍自定义服务,遇到异常时优先回看日志和权限部分。
熟练后,可以进一步学习服务依赖、定时任务(systemd timer)等高级功能。