系统管理 / 命令文档

Linux systemctl 命令

$ systemctl 22 个章节 Linux 命令详解

概述

掌握现代Linux服务管理的核心工具

概述 基础操作 状态查看 高级功能 实战案例 故障排除

什么是 systemctl?

systemctl 是 systemd 系统的核心命令行工具,用于管理系统服务(守护进程)、挂载点、设备和其他由 systemd 管理的单元。它是现代 Linux 发行版中服务管理的标准工具。

主要功能

服务控制

启动、停止、重启、重载服务配置

开机自启

设置服务开机自动启动或禁用

状态监控

查看服务运行状态和详细信息

日志管理

与 journalctl 集成查看服务日志

与传统 service 命令的区别

特性systemctl (systemd)service (SysV)
并行启动支持串行启动
依赖管理自动处理手动管理
资源限制内置支持需要额外工具
日志集成journald 集成分散日志

服务基本控制

# 启动服务

sudo systemctl start nginx

启动 nginx 服务

# 停止服务

sudo systemctl stop nginx

停止 nginx 服务

# 重启服务

sudo systemctl restart nginx

重启 nginx 服务(先停止再启动)

# 重载配置

sudo systemctl reload nginx

重载 nginx 配置文件(不重启服务)

# 重载或重启

sudo systemctl reload-or-restart nginx

尝试重载配置,如果不支持则重启

开机自启管理

# 设置开机自启
sudo systemctl enable nginx
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /lib/systemd/system/nginx.service

# 禁用开机自启
sudo systemctl disable nginx
Removed /etc/systemd/system/multi-user.target.wants/nginx.service

# 启动并设置开机自启
sudo systemctl enable --now nginx
同时启动服务并设置开机自启

# 停止并禁用开机自启
sudo systemctl disable --now nginx
同时停止服务并禁用开机自启

提示:enable/disable 只影响开机自启,不影响当前运行状态。使用 --now 参数可以同时操作当前状态。

服务屏蔽与解除

# 屏蔽服务(完全禁止启动)
sudo systemctl mask nginx
Created symlink /etc/systemd/system/nginx.service → /dev/null

# 解除屏蔽
sudo systemctl unmask nginx
Removed /etc/systemd/system/nginx.service
注意:mask 会创建指向 /dev/null 的符号链接,完全阻止服务启动,连手动启动都不行!

查看服务状态

# 查看单个服务详细状态

systemctl status nginx

● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2024-01-15 10:30:25 UTC; 2h 15min ago
       Docs: man:nginx(8)
    Process: 1234 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 1235 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 1236 (nginx)
      Tasks: 5 (limit: 4915)
     Memory: 10.2M
        CPU: 45ms
     CGroup: /system.slice/nginx.service
             ├─1236 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             └─1237 nginx: worker process

# 简洁状态查看

systemctl is-active nginx

active

# 检查是否开机自启

systemctl is-enabled nginx

enabled

# 检查服务是否失败

systemctl is-failed nginx

active

列出服务

# 列出所有服务
systemctl list-units --type=service

# 列出运行中的服务
systemctl list-units --type=service --state=active

# 列出失败的服务
systemctl list-units --type=service --state=failed

# 列出所有已安装的服务(包括未启动)
systemctl list-unit-files --type=service

系统状态概览

# 显示系统整体状态
systemctl status
● server01
    State: running
     Jobs: 0 queued
   Failed: 0 units
    Since: Mon 2024-01-15 08:15:30 UTC; 4h 30min ago
   CGroup: /
           ├─user.slice
           ├─system.slice
           └─init.scope

# 查看启动耗时
systemd-analyze
Startup finished in 2.145s (kernel) + 8.923s (userspace) = 11.068s
graphical.target reached after 8.854s in userspace

# 查看服务启动时间详情
systemd-analyze blame

服务依赖管理

# 查看服务依赖

systemctl list-dependencies nginx

nginx.service
● ├─system.slice
● └─basic.target
●   ├─microcode.service
●   ├─paths.target
●   ├─slices.target
●   ├─sockets.target
●   ├─sysinit.target

# 反向查看(谁依赖这个服务)

systemctl list-dependencies --reverse nginx

系统目标管理

# 查看当前运行级别
systemctl get-default
graphical.target

# 设置默认运行级别
sudo systemctl set-default multi-user.target
Removed /etc/systemd/system/default.target.
Created symlink /etc/systemd/system/default.target → /lib/systemd/system/multi-user.target.

# 切换到救援模式
sudo systemctl rescue

# 切换到紧急模式
sudo systemctl emergency

# 重启系统
sudo systemctl reboot

# 关机
sudo systemctl poweroff

环境变量和配置覆盖

# 查看服务环境变量
systemctl show-environment

# 设置环境变量
sudo systemctl set-environment MYVAR=value

# 创建服务配置覆盖目录
sudo systemctl edit nginx
# 这会打开编辑器,创建 /etc/systemd/system/nginx.service.d/override.conf

# 重载 systemd 配置
sudo systemctl daemon-reload

提示:使用 systemctl edit 可以安全地覆盖服务配置,而不修改原始文件。

Web服务器运维

# 完整的 Nginx 部署流程
# 1. 安装后启动并设置自启
sudo systemctl enable --now nginx

# 2. 检查状态
systemctl status nginx

# 3. 配置修改后重载
sudo vim /etc/nginx/nginx.conf
sudo nginx -t  # 测试配置语法
sudo systemctl reload nginx

# 4. 查看端口占用
sudo ss -tlnp | grep :80

# 5. 查看服务日志
journalctl -u nginx -f

数据库服务管理

# MySQL/MariaDB 管理
# 启动数据库
sudo systemctl start mariadb

# 检查启动是否成功
systemctl is-active mariadb

# 如果启动失败,查看详细错误
systemctl status mariadb -l
journalctl -u mariadb --since "10 minutes ago"

# 设置开机自启
sudo systemctl enable mariadb

# 安全重启(先停止,确保数据安全后再启动)
sudo systemctl stop mariadb
sleep 5
sudo systemctl start mariadb

应用服务批量管理

# 批量操作多个服务
# 停止多个服务
sudo systemctl stop nginx mysql redis

# 启动多个服务
sudo systemctl start nginx mysql redis

# 检查多个服务状态
systemctl status nginx mysql redis

# 使用通配符操作
sudo systemctl restart 'php*'  # 重启所有 php 相关服务

# 查看所有失败的服务
systemctl list-units --failed --type=service

系统维护脚本

# 创建服务健康检查脚本
#!/bin/bash
# /usr/local/bin/service-check.sh

SERVICES=("nginx" "mysql" "redis" "php7.4-fpm")

echo "=== 服务状态检查 $(date) ==="
for service in "${SERVICES[@]}"; do
    if systemctl is-active --quiet "$service"; then
        echo "$service: 运行正常"
    else
        echo "$service: 未运行"
        echo "   尝试启动服务..."
        sudo systemctl start "$service"
        if systemctl is-active --quiet "$service"; then
            echo "   $service 启动成功"
        else
            echo "   $service 启动失败,请检查日志"
            journalctl -u "$service" -n 5 --no-pager
        fi
    fi
done

性能监控

# 监控服务资源使用
# 查看服务内存使用
systemctl status nginx | grep Memory

# 查看服务 CPU 使用
systemctl status nginx | grep CPU

# 实时监控系统服务
watch -n 2 'systemctl list-units --type=service --state=active'

# 查看服务详细属性
systemctl show nginx --property=MainPID,LoadState,ActiveState,SubState,MemoryCurrent

# 分析启动性能
systemd-analyze critical-chain nginx.service

常见问题诊断

服务无法启动

# 1. 查看详细状态
systemctl status service-name -l

# 2. 查看启动日志
journalctl -u service-name -n 50

# 3. 检查配置文件语法
# (针对具体服务,如 nginx -t)

服务频繁重启

# 1. 查看重启历史
journalctl -u service-name | grep -i restart

# 2. 检查资源限制
systemctl show service-name | grep -i limit

# 3. 查看系统资源
top -p $(systemctl show --property MainPID --value service-name)

日志分析技巧

# 实时查看服务日志
journalctl -u nginx -f

# 查看最近的错误日志
journalctl -u nginx -p err --since today

# 查看特定时间段日志
journalctl -u nginx --since "2024-01-15 10:00:00" --until "2024-01-15 11:00:00"

# 查看开机启动日志
journalctl -b -u nginx

# 查看内核相关消息
journalctl -k --since "1 hour ago"

紧急恢复操作

紧急情况处理 # 系统无法正常启动时 # 1. 进入救援模式 systemctl rescue # 2. 进入紧急模式(最小系统) systemctl emergency # 3. 重新挂载文件系统为读写 mount -o remount,rw / # 4. 修复关键服务 systemctl reset-failed service-name systemctl start service-name # 5. 重载所有配置 systemctl daemon-reload

性能问题排查

# 分析系统启动瓶颈
systemd-analyze blame | head -20

# 生成启动链分析
systemd-analyze critical-chain

# 生成启动时间图表(需要图形界面)
systemd-analyze plot > bootup.svg

# 查看当前活跃任务
systemctl list-jobs

# 检查服务依赖问题
systemctl list-dependencies --failed

同分类 · 其他命令文档