Linux · 2 分钟阅读
系统服务配置
systemctl是和 systemd 打交道的统一入口,2026 年它已经是所有主流发行版的事实标准。service/chkconfig这种 SysV 老命令基本只剩兼容层。
服务单元
以 .service 结尾的 unit 文件。enable 时会在 /etc/systemd/system/<target>.wants/ 下建软链。
查看
systemctl list-unit-files --type=service
systemctl list-units --type=service --state=running
systemctl status nginx
systemctl cat nginx
systemctl show nginx
状态
| 状态 | 含义 |
|---|---|
enabled |
开机自启 |
disabled |
不自启 |
static |
只能被依赖,不能直接 enable |
masked |
禁止启动(被 symlink 到 /dev/null) |
启停
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx
systemctl try-restart nginx # 运行时才 restart
systemctl reload-or-restart nginx
启用
systemctl enable nginx
systemctl disable nginx
systemctl enable --now nginx # enable + start
失败排查
systemctl --failed
systemctl reset-failed nginx
journalctl -xeu nginx
全局
systemctl daemon-reload # 改 unit 后必跑
systemctl isolate multi-user.target
systemctl rescue # 进入救援模式
systemctl hibernate / suspend # 电源管理
配置文件位置
| 路径 | 用途 |
|---|---|
/etc/systemd/system/ |
系统管理员 / 自定义 |
/usr/lib/systemd/system/ |
软件包自带 |
改包内文件会被升级覆盖,正确做法是
cp到/etc/systemd/system/再改。
模板单元(template)
支持通配符:
systemctl start sshd@22.service
systemctl start sshd@2222.service
# /etc/systemd/system/sshd@.service
[Unit]
Description=OpenBSD Secure Shell server on port %I
[Service]
ExecStart=/usr/sbin/sshd -D -p %I
%I是模板实例名。
简单示例
# /etc/systemd/system/myapp.service
[Unit]
Description=My App
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/myapp
Restart=always
[Install]
WantedBy=multi-user.target
一些经验
- 改了 unit 一定
daemon-reload enable不等于start;enable --now一步到位- 用
systemd-analyze blame看启动慢在哪 - 服务挂掉想保留现场:
systemctl edit nginx加[Service] LimitCORE=infinity后重启抓 core - 关键服务
Restart=always配合StartLimitIntervalSec防止重启风暴