本帖最后由 非凡云 于 2025-6-13 16:30 编辑
systemctl 是管理和控制 systemd 系统和服务管理器的主要命令行工具。systemd 是现代 Linux 发行版(如 RHEL/CentOS 7+, Fedora, Debian 8+, Ubuntu 15.04+, openSUSE, Arch Linux 等)默认采用的初始化系统(init system)和服务管理器,取代了传统的 SysVinit。 systemctl 用于管理系统的各个方面,包括系统服务(守护进程)、挂载点、套接字、设备等(这些都被称为 Unit)。 一、核心概念Unit (单元): systemd 管理的基本对象。每个单元由一个配置文件(通常以 .service, .socket, .mount, .device, .timer 等结尾)定义。
服务单元 (.service): 最常用的单元类型,代表一个后台服务/守护进程(如 nginx, sshd, docker)。 其他单元类型:挂载点 (.mount), 套接字 (.socket), 设备 (.device), 交换空间 (.swap), 路径 (.path), 定时器 (.timer - 类似 cron), 切片 (.slice - 资源管理), 范围 (.scope - 临时进程组) 等。
Unit 文件: 定义单元行为的配置文件。通常位于:
Target (目标): 一种特殊的单元(.target),用于将多个单元分组在一起,实现特定的系统状态(类似于 SysVinit 中的运行级别,但更灵活),如 multi-user.target (多用户命令行), graphical.target (图形界面), reboot.target 等。
二、常用 systemctl 命令详解
1. 查看系统状态和信息列出所有活动单元:
- systemctl list-units
- systemctl # 不加参数等同于 `list-units`
复制代码 列出所有已安装单元(包括不活动的):
- systemctl list-unit-files
复制代码 检查系统整体状态:
检查特定单元的状态:
- systemctl status <unit-name>
- # 例如:
- systemctl status nginx.service
- systemctl status sshd
复制代码 查看某个单元的依赖关系:
- systemctl list-dependencies <unit-name>
- systemctl list-dependencies <unit-name> --reverse # 查看谁依赖它
复制代码 2. 启动、停止、重启、重载服务
启动一个服务:
- systemctl start <unit-name>
- # 例如:systemctl start apache2.service
复制代码 停止一个服务:
- systemctl stop <unit-name>
- # 例如:systemctl stop docker.service
复制代码 重启一个服务:
- systemctl restart <unit-name> # 先停止再启动
- # 例如:systemctl restart nginx.service
复制代码 重载一个服务:
- systemctl reload <unit-name> # 发送 SIGHUP 信号,让服务重新加载配置而不中断运行
- # 例如:systemctl reload sshd.service (重新加载 sshd 配置,已连接会话不受影响)
复制代码 启用服务开机自启:
- systemctl enable <unit-name>
- # 例如:systemctl enable mongod.service # 下次系统启动时,mongod 会自动启动
复制代码 禁用服务开机自启:
- systemctl disable <unit-name>
- # 例如:systemctl disable httpd.service # 下次系统启动时,httpd 不会自动启动
复制代码
|