阿森博客 VPS推荐
专注于真实的VPS测评

Linux进阶-服务管理:systemctl 命令详解

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 文件: 定义单元行为的配置文件。通常位于:
    • /usr/lib/systemd/system/: 软件包安装的标准位置(不要修改)。
    • /etc/systemd/system/: 管理员自定义或覆盖配置的位置(优先级最高)。
  • Target (目标): 一种特殊的单元(.target),用于将多个单元分组在一起,实现特定的系统状态(类似于 SysVinit 中的运行级别,但更灵活),如 multi-user.target (多用户命令行), graphical.target (图形界面), reboot.target 等。

二、常用 systemctl 命令详解
1. 查看系统状态和信息列出所有活动单元:

  1. systemctl list-units
  2. systemctl  # 不加参数等同于 `list-units`

列出所有已安装单元(包括不活动的):

  1. systemctl list-unit-files

检查系统整体状态:

  1. systemctl status

检查特定单元的状态:

  1. systemctl status <unit-name>
  2. # 例如:
  3. systemctl status nginx.service
  4. systemctl status sshd

查看某个单元的依赖关系:

  1. systemctl list-dependencies <unit-name>
  2. systemctl list-dependencies <unit-name> --reverse  # 查看谁依赖它

2. 启动、停止、重启、重载服务
启动一个服务:

  1. systemctl start <unit-name>
  2. # 例如:systemctl start apache2.service

停止一个服务:

  1. systemctl stop <unit-name>
  2. # 例如:systemctl stop docker.service

重启一个服务:

  1. systemctl restart <unit-name>  # 先停止再启动
  2. # 例如:systemctl restart nginx.service

重载一个服务:

  1. systemctl reload <unit-name>  # 发送 SIGHUP 信号,让服务重新加载配置而不中断运行
  2. # 例如:systemctl reload sshd.service  (重新加载 sshd 配置,已连接会话不受影响)

启用服务开机自启:

  1. systemctl enable <unit-name>
  2. # 例如:systemctl enable mongod.service  # 下次系统启动时,mongod 会自动启动

禁用服务开机自启:

  1. systemctl disable <unit-name>
  2. # 例如:systemctl disable httpd.service  # 下次系统启动时,httpd 不会自动启动
未经允许不得转载:阿森博客 » Linux进阶-服务管理:systemctl 命令详解