## 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 类型: ```shell systemctl -t help ``` ## 3、Unit 文件位置 常见目录: - `/usr/lib/systemd/system`:发行版提供的 unit 文件 - `/lib/systemd/system`:部分系统对应目录 - `/run/systemd/system`:运行时生成的 unit - `/etc/systemd/system`:管理员自定义或覆盖配置 优先级通常是: ```text /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-Bus - `notify`:服务启动完成后主动通知 systemd - `idle`:延后执行 ### 4.4 `[Install]` 用于定义启用或禁用时与哪些 target 建立关联。 常见字段: - `WantedBy`:被哪些 target 弱依赖 - `RequiredBy`:被哪些 target 强依赖 - `Alias`:别名 ## 5、常用 `systemctl` 命令 ### 5.1 查看运行中的 unit ```shell systemctl list-units -t service ``` ### 5.2 查看所有 unit 文件状态 ```shell systemctl list-unit-files -t service ``` ### 5.3 管理服务 ```shell systemctl start nginx systemctl stop nginx systemctl restart nginx systemctl reload nginx systemctl status nginx ``` ### 5.4 开机自启管理 ```shell systemctl enable nginx systemctl disable nginx ``` ### 5.5 重新加载配置 ```shell 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 结构和状态含义后,排查服务问题会更高效