Skip to content

systemctl 命令:系统和服务管理器

1. 命令简介

systemctl 是 systemd 系统和服务管理器的主要命令行工具。它用于控制 systemd 系统和服务管理器,可以管理系统和服务的状态。systemd 是许多现代 Linux 发行版的初始化系统和系统管理器。

2. 基本语法

bash
systemctl [选项] 命令 [单元]

3. 常用命令

  • start:启动单元
  • stop:停止单元
  • restart:重启单元
  • status:查看单元状态
  • enable:设置单元开机自启动
  • disable:禁用单元开机自启动
  • is-active:检查单元是否处于活动状态
  • is-enabled:检查单元是否已启用开机自启动
  • list-units:列出已加载的单元
  • list-unit-files:列出所有可用单元文件

4. 基础使用示例

  1. 启动服务:

    bash
    sudo systemctl start nginx
  2. 停止服务:

    bash
    sudo systemctl stop nginx
  3. 重启服务:

    bash
    sudo systemctl restart nginx
  4. 查看服务状态:

    bash
    systemctl status nginx
  5. 启用服务开机自启:

    bash
    sudo systemctl enable nginx

5. 进阶使用技巧

  1. 查看所有运行中的服务:

    bash
    systemctl list-units --type=service --state=running
  2. 重新加载 systemd 配置:

    bash
    sudo systemctl daemon-reload
  3. 查看服务的依赖关系:

    bash
    systemctl list-dependencies nginx
  4. 屏蔽服务(防止被启动):

    bash
    sudo systemctl mask nginx

6. 实用示例

  1. 创建自定义服务:
    创建文件 /etc/systemd/system/myapp.service
ini
 [Unit]
   Description=My Custom App
   After=network.target

   [Service]
   ExecStart=/path/to/myapp
   Restart=always
   User=myuser

   [Install]
   WantedBy=multi-user.target

然后启用并启动服务:

bash
sudo systemctl enable myapp
sudo systemctl start myapp
  1. 查看系统启动时间:

    bash
    systemctl --version
    systemd-analyze time
  2. 查看失败的单元:

    bash
    systemctl --failed
  3. 查看系统日志:

    bash
    journalctl -u nginx

7. 注意事项

  • 大多数 systemctl 命令需要 root 权限。
  • 修改服务文件后,需要运行 systemctl daemon-reload 重新加载配置。
  • 不同的 Linux 发行版可能有略微不同的 systemd 实现。

8. 相关命令

  • journalctl:查询 systemd 日志
  • hostnamectl:控制系统主机名
  • localectl:控制系统本地化和键盘布局
  • timedatectl:控制系统时间和日期

9. 技巧与建议

  1. 使用 systemctl edit 来安全地修改服务配置:

    bash
    sudo systemctl edit nginx
  2. 使用 systemctl cat 查看服务的完整配置:

    bash
    systemctl cat nginx
  3. 使用 systemctl list-timers 查看系统定时任务:

    bash
    systemctl list-timers
  4. 使用 systemctl isolate 切换系统运行级别:

    bash
    sudo systemctl isolate multi-user.target  # 切换到多用户模式

systemctl 是现代 Linux 系统中管理服务和系统状态的核心工具。它提供了一个统一的接口来控制 systemd 系统和服务管理器,使得系统管理任务变得更加简单和标准化。熟练使用 systemctl 可以帮助系统管理员更有效地管理系统服务、监控系统状态,以及进行故障排查。对于任何使用采用 systemd 的 Linux 发行版的用户来说,掌握 systemctl 都是必不可少的技能。