在现代 Linux 系统中(2015 年之后几乎所有主流发行版),systemd 已经完全取代了传统的 SysV init 和 Upstart,成为默认的 PID 1(系统初始化进程)和服务管理器。
理解 systemd 的服务管理方式,是 Linux 服务器运维最核心的基础技能之一。本文聚焦最常用、最实操的用法,帮助新手快速上手。
| 概念 | 含义 | 常见文件后缀 | 类比(旧时代) |
|---|---|---|---|
| Unit | systemd 管理的最小单位(服务、挂载、定时器、socket 等) | .service .timer .socket .target .mount 等 | — |
| Service | 最常见的一种 Unit,代表一个后台进程/守护进程 | .service | 旧的 /etc/init.d/xxx |
| Target | 一组 Unit 的集合,类似“启动级别” | .target | runlevel 3/5 |
| systemctl | systemd 的主要命令行工具,几乎所有操作都通过它完成 | — | service / chkconfig |
| journalctl | 查看 systemd 管理的服务的日志(取代 /var/log/messages 等部分功能) | — | tail -f /var/log/xxx |
最常用的目标(target):
| 操作类型 | 命令示例 | 说明 |
|---|---|---|
| 查看状态 | systemctl status nginx | 显示服务当前状态、PID、主进程、最近日志 |
| 启动服务 | systemctl start nginx | 立即启动(不影响开机自启) |
| 停止服务 | systemctl stop nginx | 立即停止 |
| 重启服务 | systemctl restart nginx | 停止 → 启动 |
| 重新加载配置 | systemctl reload nginx | 不中断服务,重新读配置(nginx 支持) |
| 设置开机自启 | systemctl enable nginx | 创建符号链接到 multi-user.target.wants/ |
| 取消开机自启 | systemctl disable nginx | 删除符号链接 |
| 一次性启动 | systemctl start nginx --now | 启动 + 同时 enable |
| 查看所有服务 | systemctl list-units --type=service | 当前加载的服务 |
| 查看已安装服务 | systemctl list-unit-files --type=service | 看哪些服务是 enabled / disabled |
| 查看失败的服务 | systemctl --failed | 快速定位启动失败的服务 |
| 查看依赖关系 | systemctl list-dependencies nginx | 看 nginx 依赖哪些 target 和服务 |
执行 systemctl status nginx 后,最重要的几行信息:
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2026-02-10 14:30:22 PST; 3h ago
Main PID: 1234 (nginx)
Tasks: 5 (limit: 4915)
Memory: 28.4M
CPU: 1.203s
CGroup: /system.slice/nginx.service
├─1234 nginx: master process /usr/sbin/nginx
└─1235 nginx: worker process
关键字段含义:
systemd 把所有服务的标准输出/错误都收集到 journald 中。
最常用组合:
场景 1:新装 nginx,想让它开机自启并立即启动
sudo systemctl enable --now nginx
# 等价于
sudo systemctl enable nginx
sudo systemctl start nginx
场景 2:修改了配置文件,想让服务重新加载配置而不中断连接
sudo systemctl reload nginx
# 如果服务不支持 reload,就只能 restart
场景 3:服务启动失败,想知道为什么
systemctl status nginx # 先看 Active: failed 那一行
journalctl -u nginx -xe # -xe 显示最近日志并解释错误码
场景 4:想临时禁止某个服务开机启动,但不影响当前运行
sudo systemctl mask nginx # 屏蔽(连 start 命令都会失败)
# 恢复
sudo systemctl unmask nginx
场景 5:查看系统启动时哪个服务最耗时
systemd-analyze blame | head -15
误区 1:以为 service nginx restart 还能用 → 大部分现代系统已废弃 service 命令,强制使用 systemctl
误区 2:直接 kill -9 主进程来“重启”服务 → 会导致 systemd 认为服务异常退出,可能触发重启策略或标记 failed
误区 3:配置文件改了却不起作用 → 改的是 /etc/nginx/nginx.conf,但没执行 reload/restart
正确做法总结口诀:
掌握以上内容后,你已经能处理 90% 的日常服务管理任务(启动、停止、重启、日志查看、开机自启、故障定位)。后续可以深入的方向包括:编写/修改 .service 文件、理解 drop-in 覆盖机制、使用 systemd timer 替代 crontab、cgroup v2 资源限制、socket 激活等高级特性。