Skip to content

在 systemd 中管理服务

在这篇文章中

systemd 是大多数现代 Linux 发行版中的标准 init 系统和服务管理器:

  • Ubuntu 16.04+(强烈推荐使用 Ubuntu 20.04/22.04/24.04)
  • Debian 8+(Debian 11/12 – 当前 LTS 版本)
  • RHEL/CentOS 7+(RHEL 9 / AlmaLinux/Rocky Linux 9 – 现代 CentOS 替代品)
  • Fedora、openSUSE、Arch 等

内核启动后,会将控制权交给 systemd(PID 1),它负责:

  • 启动和停止服务,
  • 挂载文件系统,
  • 配置网络和环境,
  • 管理组件之间的依赖关系。

与 systemd 交互的主要接口是工具 systemctl

基本语法

systemctl [options] command [service]

备注

在大多数情况下,使用 systemctl 需要超级用户权限——请使用 sudo

查看服务状态

任务 命令
列出 active 单元(服务、套接字、计时器等) systemctl list-units
仅列出 正在运行的服务 systemctl list-units --type=service
所有服务(包括已停止和非活动状态) systemctl list-units --type=service --all
列出 正在运行 的服务 systemctl list-units --type=service --state=running
搜索特定服务(例如 nginx) systemctl list-units '*nginx*'
服务的详细信息 systemctl status nginx (包含日志、PID、依赖关系)

备注

添加 --no-pager 以防止输出分页(例如 systemctl status nginx --no-pager)。

管理服务运行

我们将以 nginx 为例,但这些命令适用于 任何 服务:sshdpostgresqlclamav-daemondocker 等。

操作 命令 备注
检查状态 sudo systemctl status nginx 显示是否正在运行、其 PID、最近日志和错误
启动 sudo systemctl start nginx 启动服务,直到下次重启
停止 sudo systemctl stop nginx
重启 sudo systemctl restart nginx 完全停止 > 启动(如果未运行,则会启动)
不重启的情况下重新加载配置 sudo systemctl reload nginx 如果服务支持 SIGHUP(nginx、Apache、Postfix 等)则有效
重新加载或重启 sudo systemctl reload-or-restart nginx 如果不支持 reload,则回退到 restart
尝试重启(仅当正在运行时) sudo systemctl try-restart nginx 对脚本安全
检查服务是否处于活动状态 systemctl is-active nginx 输出:active / inactive / unknown
检查服务是否失败 systemctl is-failed nginx 如果服务因错误退出,则输出:failed

备注

start/restart 之后,服务 不会 在重启时自动启动——自动启动需要单独配置。

管理自动启动

操作 命令 会发生什么
启用自动启动 sudo systemctl enable nginx /usr/lib/systemd/system/nginx.service 创建符号链接到 /etc/systemd/system/multi-user.target.wants/
禁用自动启动 sudo systemctl disable nginx 移除符号链接,但 不会 停止正在运行的进程
检查自动启动状态 systemctl is-enabled nginx 可能的值:enableddisabledstaticmasked
重置设置 > 重新启用 sudo systemctl reenable nginx 清除之前的覆盖设置并重新启用服务
重置为默认值 sudo systemctl preset nginx 将任何自定义设置恢复为发行版默认值(很少使用)

高级功能

1. 强制重新加载 systemd 配置

如果你编辑了 .service 文件:

sudo systemctl daemon-reload
sudo systemctl restart nginx

2. 查看依赖关系

systemctl list-dependencies nginx

3. 服务日志(通过 journalctl

journalctl -u nginx

4. 屏蔽服务(完全禁用,即使手动也无法启动)

sudo systemctl mask nginx
sudo systemctl unmask nginx

日常使用的有用命令

# 快速检查服务是否已启用并正在运行
systemctl is-active --quiet nginx && echo "OK" || echo "STOPPED"


# 使用单个命令启动并启用自动启动
sudo systemctl start nginx && sudo systemctl enable nginx


# 禁用并停止服务
sudo systemctl stop nginx && sudo systemctl disable nginx

备注

--now 标志(自 systemd v220+,2015 年起可用)同时执行 enable + startdisable + stop

question_mark
Is there anything I can help you with?
question_mark
AI Assistant ×