3.8 KiB
3.8 KiB
1、Systemd 概览
从 CentOS 7 及很多现代 Linux 发行版开始,systemd 成为默认的初始化系统(init system)和服务管理器。
它负责:
- 系统启动流程管理
- 服务启动、停止、重启
- 依赖关系控制
- 挂载点、socket、target 等资源管理
在日常运维中,最常接触的是 systemctl 和 service unit。
2、Unit 是什么
Systemd 使用 Unit 表示不同类型的管理对象,每种 Unit 都对应一种资源或行为。
2.1 常见 Unit 类型
service:系统服务socket:套接字target:目标组,类似传统运行级别概念mount:挂载点automount:自动挂载点swap:交换分区device:设备snapshot:系统快照
查看支持的 Unit 类型:
systemctl -t help
3、Unit 文件位置
常见目录:
/usr/lib/systemd/system:发行版提供的 unit 文件/lib/systemd/system:部分系统对应目录/run/systemd/system:运行时生成的 unit/etc/systemd/system:管理员自定义或覆盖配置
优先级通常是:
/etc > /run > /usr/lib
4、Unit 文件结构
一个典型的 service 文件通常分为 3 部分:
[Unit][Service][Install]
4.1 [Unit]
用于描述:
- 单元说明信息
- 启动顺序
- 依赖关系
常见字段:
Description:描述信息Documentation:文档说明Requires:强依赖Wants:弱依赖After:指定在某些 unit 之后启动
4.2 [Service]
用于定义服务本身的运行方式。
常见字段:
Type:服务类型ExecStart:启动命令ExecStartPre:启动前执行ExecStartPost:启动后执行ExecReload:重载命令EnvironmentFile:环境变量文件Restart:失败后是否重启RestartSec:重启前等待时间
4.3 常见 Type
simple:默认类型,前台运行forking:启动后派生子进程,父进程退出oneshot:执行一次即退出dbus:依赖 D-Busnotify:服务启动完成后主动通知 systemdidle:延后执行
4.4 [Install]
用于定义启用或禁用时与哪些 target 建立关联。
常见字段:
WantedBy:被哪些 target 弱依赖RequiredBy:被哪些 target 强依赖Alias:别名
5、常用 systemctl 命令
5.1 查看运行中的 unit
systemctl list-units -t service
5.2 查看所有 unit 文件状态
systemctl list-unit-files -t service
5.3 管理服务
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx
systemctl status nginx
5.4 开机自启管理
systemctl enable nginx
systemctl disable nginx
5.5 重新加载配置
systemctl daemon-reload
修改或新增 unit 文件后,经常需要执行这条命令。
6、常见状态理解
6.1 运行状态
loaded:配置文件已加载active (running):正在运行active (exited):一次性任务已成功执行完inactive:未运行failed:运行失败
6.2 开机启动状态
enabled:开机自动启动disabled:不开机自动启动static:不能单独 enable,通常被其他 unit 依赖激活indirect:间接启用
7、常见运维建议
- 改 unit 文件后记得
daemon-reload - 排查服务问题时先看
systemctl status - 再结合
journalctl -u 服务名看日志 - 依赖关系问题要重点看
Requires/Wants/After - 自定义服务建议放在
/etc/systemd/system
8、小结
systemd是现代 Linux 的核心初始化与服务管理系统- Unit 是它管理资源的基本对象
- 最常见的是
service和target systemctl是日常管理服务的主力命令- 掌握 unit 结构和状态含义后,排查服务问题会更高效