使用 systemctl 管理 Linux 服务
Systemd 是大多数现代 Linux 发行版的默认初始化系统。systemctl 命令是管理服务的主要工具。本文介绍最常用的操作。
1. 查看服务状态
查看某个服务是否正在运行:
systemctl status nginx
输出中包含活动状态、主进程 PID、内存占用和最近的日志条目。绿色的 active running 表示服务运行正常。
列出所有正在运行的服务:
systemctl list-units --type=service --state=running
2. 启动和停止服务
立即启动服务:
systemctl start nginx
停止正在运行的服务:
systemctl stop nginx
重启服务:
systemctl restart nginx
在不完全重启的情况下重新加载配置:
systemctl reload nginx
3. 启用和禁用服务
启用服务使其在开机时自动启动:
systemctl enable nginx
禁用服务使其不在开机时启动:
systemctl disable nginx
一条命令同时启用并启动:
systemctl enable --now nginx
4. 使用 journalctl 查看日志
Systemd 通过 journald 收集日志。查看特定服务的日志:
journalctl -u nginx
实时跟踪日志:
journalctl -u nginx -f
仅显示最近 50 条记录:
journalctl -u nginx -n 50
按时间范围过滤:
journalctl -u nginx --since "2026-06-10" --until "2026-06-11"
5. 编辑服务文件
在不修改包自带的配置文件的情况下覆盖服务配置:
systemctl edit nginx
这会打开一个编辑器并创建覆盖文件。修改后需要重新加载:
systemctl daemon-reload
systemctl restart nginx
6. 常见故障排查步骤
当服务启动失败时:
- 查看状态输出中的错误信息
- 使用 journalctl -u servicename -n 50 查看最近日志
- 验证配置文件语法是否正确
- 检查依赖项(其他服务、网络、文件)是否可用
- 检查服务单元文件中的路径或权限问题
服务卡在 failed 状态时可以重置:
systemctl reset-failed nginx
总结
systemctl 在大多数 Linux 发行版上提供了统一的服务管理接口。最常用的命令是 status、start、stop、restart、enable 和 disable。结合 journalctl 查看日志,这些工具涵盖了日常服务管理的主要任务。