openEuler欧拉操作系统–服务管理类命令超详细使用教程

admin 2026-03-03 07:31:18 网络安全文章 来源:ZONE.CI 全球网 0 阅读模式

文章总结: 该文档详细讲解了openEuler系统中systemd服务管理工具systemctl的使用方法。内容涵盖架构解析、单元文件管理、服务启停控制及自启配置等核心操作。通过丰富的命令示例与状态说明表格,系统展示了服务状态监控、依赖管理及故障排查的实战技巧,为运维人员提供了从基础到进阶的标准操作指南,具备极高的实战参考价值。 综合评分: 85 文章分类: 安全运营,实战经验


cover_image

openEuler 欧拉操作系统 – 服务管理类命令超详细使用教程

原创

刘军军 刘军军

运维星火燎原

2026年2月23日 00:00 山西

目录

  1. 服务管理简介
  2. systemd 架构详解
  3. systemctl 命令基础
  4. 服务状态管理
  5. 服务启动/停止/重启
  6. 开机自启配置
  7. 服务单元文件详解
  8. 自定义服务创建
  9. 服务依赖管理
  10. 服务日志查看
  11. 服务资源限制
  12. 定时器服务
  13. 目标 (Target) 管理
  14. 服务故障排查
  15. 常见服务配置示例
  16. 自动化脚本
  17. 与旧命令对比
  18. 速查表

一、服务管理简介

1.1 什么是服务管理

服务管理是 Linux 系统管理的核心功能,用于控制后台运行的守护进程(daemon)。openEuler 使用 systemd 作为初始化系统和服务管理器。

# 查看初始化系统
ps -p 1 -o comm=

# 输出
systemd

# 查看 systemd 版本
systemctl --version

# 输出示例
systemd 249 (249-106.oe2203)
+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP etc.

1.2 为什么使用 systemd

| | | | — | — | | 优势 | 说明 | | 并行启动 | 加速系统启动过程 | | 按需启动 | 按需激活服务 | | 依赖管理 | 自动处理服务依赖 | | 统一配置 | 统一的单元文件格式 | | 日志集成 | 与 journalctl 深度集成 | | 资源控制 | 集成 cgroups 资源管理 | | 向后兼容 | 兼容 SysV init 脚本 |

1.3 服务管理工具对比

| | | | | — | — | — | | 工具 | 说明 | 状态 | | systemctl | systemd 管理命令 | ✅ 推荐 | | service | SysV 兼容命令 | ⚠️ 兼容用 | | chkconfig | SysV 自启管理 | ⚠️ 兼容用 | | init | 传统 init 命令 | ❌ 已废弃 |

1.4 验证服务管理环境

# 检查 systemd 是否运行
pidof systemd

# 检查 systemd 状态
systemctl status

# 查看默认目标
systemctl get-default

# 列出所有单元类型
systemctl list-unit-files --type=service

二、systemd 架构详解

2.1 systemd 架构图

┌─────────────────────────────────────────────────────────┐
│                    用户空间                              │
├─────────────────────────────────────────────────────────┤
│  systemctl  │  journalctl  │  systemd-analyze  │  其他   │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│                  systemd 核心                            │
├─────────────────────────────────────────────────────────┤
│  单元管理  │  依赖解析  │  并行启动  │  资源控制  │  日志  │
└─────────────────────────────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────┐
│                  内核空间                                │
├─────────────────────────────────────────────────────────┤
│  cgroups  │  namespaces  │  inotify  │  netlink  │  ...  │
└─────────────────────────────────────────────────────────┘

2.2 单元 (Unit) 类型

| | | | | — | — | — | | 类型 | 扩展名 | 说明 | | Service | .service | 系统服务 | | Target | .target | 运行级别/目标 | | Socket | .socket | 套接字激活 | | Device | .device | 设备管理 | | Mount | .mount | 挂载点 | | Automount | .automount | 自动挂载 | | Timer | .timer | 定时任务 | | Path | .path | 路径监控 | | Slice | .slice | 资源切片 | | Scope | .scope | 外部进程组 |

2.3 单元文件位置

# 系统单元目录(优先级最高)
/etc/systemd/system/

# 系统单元目录(次优先级)
/usr/lib/systemd/system/

# 运行时单元目录(临时)
/run/systemd/system/

# 用户单元目录
~/.config/systemd/user/

# 查看单元文件路径
systemctl show nginx.service -p FragmentPath

# 输出
FragmentPath=/usr/lib/systemd/system/nginx.service

2.4 单元加载优先级

优先级从高到低:
1. /etc/systemd/system/          # 管理员自定义
2. /run/systemd/system/          # 运行时生成
3. /usr/lib/systemd/system/      # 软件包安装

三、systemctl 命令基础

3.1 命令语法

systemctl [选项] [命令] [单元名...]

3.2 常用选项

| | | | — | — | | 选项 | 说明 | | -h, –help | 显示帮助 | | –version | 显示版本 | | -t, –type= | 指定单元类型 | | -a, –all | 显示所有单元 | | –failed | 显示失败单元 | | –no-pager | 不使用分页 | | –no-legend | 不显示图例 | | -l, –full | 完整显示 | | –force | 强制执行 | | –now | 立即生效 | | –user | 用户模式 | | –global | 全局用户配置 |

3.3 常用命令

| | | | — | — | | 命令 | 说明 | | start | 启动服务 | | stop | 停止服务 | | restart | 重启服务 | | reload | 重载配置 | | status | 查看状态 | | enable | 启用自启 | | disable | 禁用自启 | | is-active | 检查是否运行 | | is-enabled | 检查是否自启 | | list-units | 列出单元 | | list-unit-files | 列出单元文件 | | cat | 显示单元文件 | | edit | 编辑单元文件 | | mask | 屏蔽服务 | | unmask | 取消屏蔽 |

3.4 基本使用示例

# 查看 systemctl 帮助
systemctl --help

# 查看版本
systemctl --version

# 查看系统状态
systemctl status

# 输出示例
$ systemctl status
● server01
    State: running
     Jobs: 0 queued
   Failed: 0 units
    Since: Thu 2024-01-15 10:00:00 CST; 5 days ago
   CGroup: /
           ├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 22
           ├─256 /usr/sbin/sshd -D
           └─300 /usr/sbin/nginx -g daemon off;

四、服务状态管理

4.1 查看服务状态

# 查看单个服务状态
systemctl status nginx

# 输出详解
$ systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2024-01-15 10:00:00 CST; 5 days ago
     Docs: man:nginx(8)
 Main PID: 1234 (nginx)
    Tasks: 5 (limit: 4915)
   Memory: 10.5M
      CPU: 1.234s
   CGroup: /system.slice/nginx.service
           ├─1234 nginx: master process /usr/sbin/nginx -g daemon off;
           └─1235 nginx: worker process

# 字段说明
Loaded:    单元文件加载状态
Active:    当前活动状态
Main PID:  主进程 ID
Tasks:     任务数
Memory:    内存使用
CPU:       CPU 使用
CGroup:    控制组路径

4.2 服务状态说明

| | | | — | — | | 状态 | 说明 | | active (running) | 正在运行 | | active (exited) | 已成功执行并退出 | | active (waiting) | 运行中但等待事件 | | inactive (dead) | 未运行 | | activating (start) | 启动中 | | deactivating (stop) | 停止中 | | failed | 启动失败 | | masked | 已屏蔽 |

4.3 列出服务

# 列出所有加载的单元
systemctl list-units

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

# 列出所有活动服务
systemctl list-units --type=service --state=active

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

# 列出所有单元文件
systemctl list-unit-files

# 列出所有服务单元文件
systemctl list-unit-files --type=service

# 列出已启用的服务
systemctl list-unit-files --type=service --state=enabled

# 列出已禁用的服务
systemctl list-unit-files --type=service --state=disabled

# 简洁输出(适合脚本)
systemctl list-units --type=service --no-legend --plain

# 输出示例
$ systemctl list-units --type=service --state=active
  UNIT                LOAD   ACTIVE SUB     DESCRIPTION
  crond.service       loaded active running Command Scheduler
  firewalld.service   loaded active running firewalld - dynamic firewall daemon
  nginx.service       loaded active running The nginx HTTP andreverse proxy server
  sshd.service        loaded active running OpenSSH server daemon
  systemd-journald.service loaded active running Journal Service

  LOAD   = Reflects whether the unit definition was properly loaded.
  ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
  SUB    = The low-level unit activation state, values depend on unit type.

5 loaded units listed.

4.4 过滤和搜索

# 按名称过滤
systemctl list-units --type=service | grep nginx

# 按状态过滤
systemctl list-units --type=service --state=failed

# 按加载状态过滤
systemctl list-units --type=service --load-state=loaded

# 显示所有(包括未加载的)
systemctl list-units --all

# 显示完整单元名
systemctl list-units --full

# 不显示图例
systemctl list-units --no-legend

4.5 服务树状显示

# 查看服务进程树
systemctl status nginx | grep -A 20 "CGroup"

# 使用 systemd-cgtop 查看资源使用
systemd-cgtop

# 使用 systemd-cgls 查看控制组
systemd-cgls

# 查看特定服务的控制组
systemd-cgls /system.slice/nginx.service

五、服务启动/停止/重启

5.1 启动服务

# 启动服务
sudo systemctl start nginx

# 启动多个服务
sudo systemctl start nginx mysql php-fpm

# 启动服务并显示详细输出
sudo systemctl --verbose start nginx

# 启动服务并等待完成
sudo systemctl start --wait nginx

# 验证启动
systemctl is-active nginx
systemctl status nginx

5.2 停止服务

# 停止服务
sudo systemctl stop nginx

# 停止多个服务
sudo systemctl stop nginx mysql php-fpm

# 强制停止
sudo systemctl kill nginx

# 发送特定信号停止
sudo systemctl kill --kill-who=main --signal=SIGTERM nginx

# 验证停止
systemctl is-active nginx
# 输出:inactive

5.3 重启服务

# 重启服务
sudo systemctl restart nginx

# 重启并等待完成
sudo systemctl restart --wait nginx

# 条件重启(仅在运行时重启)
sudo systemctl condrestart nginx

# 重启多个服务
sudo systemctl restart nginx mysql

# 验证重启
systemctl is-active nginx
systemctl show nginx -p MainPID

5.4 重载配置

# 重载服务配置(不中断服务)
sudo systemctl reload nginx

# 重启或重载(如果支持重载则重载)
sudo systemctl reload-or-restart nginx

# 重载或重启(如果支持重载则重载,否则重启)
sudo systemctl reload-or-restart nginx

# 重载 systemd 配置
sudo systemctl daemon-reload

# 何时需要 daemon-reload
# 1. 修改了单元文件
# 2. 添加了新的单元文件
# 3. 修改了单元文件链接

5.5 服务操作组合

# 重启并验证
sudo systemctl restart nginx && systemctl is-active nginx

# 停止并禁用
sudo systemctl stop nginx && sudo systemctl disable nginx

# 启用并启动
sudo systemctl enable nginx && sudo systemctl start nginx

# 重载配置并重启
sudo systemctl daemon-reload && sudo systemctl restart nginx

# 批量重启服务
for service in nginx mysql redis; do
    sudo systemctl restart $service
    echo"$service: $(systemctl is-active $service)"
done

5.6 服务操作超时控制

# 设置启动超时
sudo systemctl start --timeout=30s nginx

# 设置停止超时
sudo systemctl stop --timeout=30s nginx

# 查看默认超时
systemctl show nginx -p TimeoutStartUSec
systemctl show nginx -p TimeoutStopUSec

六、开机自启配置

6.1 启用开机自启

# 启用服务开机自启
sudo systemctl enable nginx

# 输出
Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.

# 启用并立即启动
sudo systemctl enable --now nginx

# 启用多个服务
sudo systemctl enable nginx mysql redis

# 强制启用
sudo systemctl enable --force nginx

6.2 禁用开机自启

# 禁用服务开机自启
sudo systemctl disable nginx

# 输出
Removed /etc/systemd/system/multi-user.target.wants/nginx.service.

# 禁用但不立即停止
sudo systemctl disable nginx

# 禁用并立即停止
sudo systemctl disable --now nginx

# 禁用多个服务
sudo systemctl disable nginx mysql redis

6.3 检查自启状态

# 检查是否启用自启
systemctl is-enabled nginx

# 输出
enabled

# 检查并显示详细状态
systemctl is-enabled nginx --quiet && echo"已启用" || echo"未启用"

# 检查是否激活(运行中)
systemctl is-active nginx

# 输出
active

# 综合检查
systemctl is-enabled nginx && systemctl is-active nginx && echo"服务正常"

# 检查自启状态列表
systemctl list-unit-files --type=service | grep nginx

6.4 自启状态说明

| | | | — | — | | 状态 | 说明 | | enabled | 已启用自启 | | disabled | 已禁用自启 | | static | 静态(不能被启用) | | masked | 已屏蔽 | | indirect | 间接启用 | | enabled-runtime | 运行时启用 | | linked | 已链接 | | generated | 已生成 |

6.5 自启配置位置

# 查看自启链接
ls -la /etc/systemd/system/multi-user.target.wants/

# 查看服务安装位置
systemctl show nginx -p Install

# 输出
Install=WantedBy=multi-user.target

# 查看单元文件路径
systemctl show nginx -p FragmentPath

# 查看自启目标
systemctl list-dependencies multi-user.target

6.6 修改默认启动目标

# 查看当前默认目标
systemctl get-default

# 输出
multi-user.target

# 设置默认目标为图形界面
sudo systemctl set-default graphical.target

# 设置默认目标为多用户(命令行)
sudo systemctl set-default multi-user.target

# 设置默认目标为救援模式
sudo systemctl set-default rescue.target

# 临时切换到目标
sudo systemctl isolate multi-user.target
sudo systemctl isolate graphical.target

# 常见目标
# multi-user.target    - 多用户命令行
# graphical.target     - 图形界面
# rescue.target        - 救援模式
# emergency.target     - 紧急模式
# poweroff.target      - 关机
# reboot.target        - 重启

七、服务单元文件详解

7.1 查看单元文件

# 查看单元文件内容
systemctl cat nginx

# 输出示例
$ systemctl cat nginx
# /usr/lib/systemd/system/nginx.service
[Unit]
Description=The nginx HTTP and reverse proxy server
Documentation=man:nginx(8)
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

7.2 单元文件结构

# ================================
# [Unit] 部分 - 单元元数据
# ================================
[Unit]
# 服务描述
Description=服务描述信息

# 文档链接
Documentation=man:service(8)

# 启动顺序(在这些单元之后启动)
After=network.target syslog.target

# 启动顺序(在这些单元之前启动)
Before=multi-user.target

# 依赖关系(必须成功启动)
Requires=network.target

# 依赖关系(如果失败不影响本服务)
Wants=network.target

# 冲突关系(不能同时运行)
Conflicts=other.service

# 启动条件
ConditionPathExists=/etc/service/config
ConditionUser=!root

# ================================
# [Service] 部分 - 服务配置
# ================================
[Service]
# 服务类型
Type=forking

# 主进程 PID 文件
PIDFile=/run/service.pid

# 启动命令
ExecStart=/usr/bin/service --start

# 启动前命令
ExecStartPre=/usr/bin/service --check

# 停止命令
ExecStop=/usr/bin/service --stop

# 重载命令
ExecReload=/usr/bin/service --reload

# 重启命令
ExecRestart=/usr/bin/service --restart

# 运行用户
User=service

# 运行组
Group=service

# 工作目录
WorkingDirectory=/var/service

# 环境变量
Environment="VAR1=value1"
EnvironmentFile=/etc/service/env

# 重启策略
Restart=on-failure

# 重启延迟
RestartSec=5s

# 启动超时
TimeoutStartSec=90s

# 停止超时
TimeoutStopSec=90s

# 发送信号
KillMode=process
KillSignal=SIGTERM

# 资源限制
LimitNOFILE=65535
LimitNPROC=65535

# 安全选项
PrivateTmp=yes
ProtectSystem=full
ProtectHome=yes
NoNewPrivileges=yes

# ================================
# [Install] 部分 - 安装配置
# ================================
[Install]
# 启用时创建的目标链接
WantedBy=multi-user.target

# 启用时创建的目标要求
RequiredBy=service.target

# 别名
Alias=myservice.service

7.3 服务类型详解

| | | | | — | — | — | | 类型 | 说明 | 适用场景 | | simple | 默认类型,主进程不 fork | 大多数现代服务 | | forking | 主进程 fork 后退出 | 传统守护进程 | | oneshot | 执行一次后退出 | 初始化脚本 | | dbus | 通过 D-Bus 激活 | D-Bus 服务 | | notify | 发送通知表示就绪 | 支持 sd_notify 的服务 | | idle | 延迟到所有 active 任务完成 | 后台任务 |

7.4 查看单元属性

# 查看所有属性
systemctl show nginx

# 查看特定属性
systemctl show nginx -p MainPID
systemctl show nginx -p ExecMainStartTimestamp
systemctl show nginx -p MemoryCurrent
systemctl show nginx -p CPUUsageNSec

# 查看多个属性
systemctl show nginx -p MainPID -p MemoryCurrent -p CPUUsageNSec

# 查看重启策略
systemctl show nginx -p Restart -p RestartSec

# 查看超时设置
systemctl show nginx -p TimeoutStartUSec -p TimeoutStopUSec

# 查看依赖关系
systemctl show nginx -p Requires -p Wants -p After -p Before

八、自定义服务创建

8.1 创建简单服务

# 创建服务脚本
cat > /usr/local/bin/myapp.sh <<&nbsp;'EOF'
#!/bin/bash
echo"MyApp started at&nbsp;$(date)"&nbsp;>> /var/log/myapp.log
whiletrue;&nbsp;do
&nbsp; &nbsp; sleep 60
&nbsp; &nbsp;&nbsp;echo"MyApp running at&nbsp;$(date)"&nbsp;>> /var/log/myapp.log
done
EOF

chmod +x /usr/local/bin/myapp.sh

# 创建服务单元文件
cat > /etc/systemd/system/myapp.service <<&nbsp;'EOF'
[Unit]
Description=My Custom Application
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/myapp.sh
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target
EOF

# 重载配置
sudo systemctl daemon-reload

# 启用并启动
sudo systemctl&nbsp;enable&nbsp;--now myapp

# 验证
systemctl status myapp

8.2 创建带环境变量的服务

# 创建环境变量文件
cat&nbsp;> /etc/myapp/env <<&nbsp;'EOF'
APP_ENV=production
APP_PORT=8080
APP_LOG_LEVEL=info
DB_HOST=localhost
DB_PORT=3306
EOF

# 创建服务单元文件
cat > /etc/systemd/system/myapp.service <<&nbsp;'EOF'
[Unit]
Description=My Custom Application
After=network.target

[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
EnvironmentFile=/etc/myapp/env
ExecStart=/opt/myapp/bin/myapp
Restart=on-failure
RestartSec=5s

# 资源限制
LimitNOFILE=65535
LimitNPROC=65535

# 安全选项
PrivateTmp=yes
ProtectSystem=full
NoNewPrivileges=yes

[Install]
WantedBy=multi-user.target
EOF

# 创建用户
sudo useradd -r -s /sbin/nologin myapp

# 重载并启动
sudo systemctl daemon-reload
sudo systemctl enable --now myapp

8.3 创建一次性服务 (oneshot)

# 创建初始化脚本
cat > /usr/local/bin/init-service.sh <<&nbsp;'EOF'
#!/bin/bash
echo"Running initialization at&nbsp;$(date)"&nbsp;>> /var/log/init-service.log
# 执行初始化任务
mkdir -p /var/data/app
chown app:app /var/data/app
echo"Initialization completed"&nbsp;>> /var/log/init-service.log
EOF

chmod +x /usr/local/bin/init-service.sh

# 创建 oneshot 服务
cat > /etc/systemd/system/init-service.service <<&nbsp;'EOF'
[Unit]
Description=Initialization Service
Before=app.service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/init-service.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

# 重载并启动
sudo systemctl daemon-reload
sudo systemctl&nbsp;enable&nbsp;init-service

8.4 创建带依赖的服务

# 创建主服务
cat > /etc/systemd/system/app.service <<&nbsp;'EOF'
[Unit]
Description=Main Application
After=network.target init-service.service mysql.service
Requires=mysql.service
Wants=redis.service

[Service]
Type=simple
User=app
ExecStart=/opt/app/bin/app
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

# 创建依赖服务
cat > /etc/systemd/system/mysql.service <<&nbsp;'EOF'
[Unit]
Description=MySQL Database

[Service]
Type=forking
ExecStart=/usr/bin/mysqld_safe
PIDFile=/var/run/mysqld/mysqld.pid

[Install]
WantedBy=multi-user.target
EOF

# 重载配置
sudo systemctl daemon-reload

8.5 服务模板(实例化服务)

# 创建模板服务文件
cat >&nbsp;/etc/systemd/system/[email protected] <<&nbsp;'EOF'
[Unit]
Description=Application Instance %i
After=network.target

[Service]
Type=simple
User=app
ExecStart=/opt/app/bin/app&nbsp;--instance %i
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

# 重载配置
sudo systemctl daemon-reload

# 启动多个实例
sudo systemctl start app@1
sudo systemctl start app@2
sudo systemctl start app@3

# 查看所有实例
systemctl list-units&nbsp;'app@*'

# 停止所有实例
sudo systemctl stop app@{1,2,3}

九、服务依赖管理

9.1 查看服务依赖

#&nbsp;查看依赖树
systemctl list-dependencies nginx

#&nbsp;查看反向依赖(哪些服务依赖此服务)
systemctl list-dependencies nginx --reverse

#&nbsp;查看直接依赖
systemctl show nginx -p Requires
systemctl show nginx -p Wants

#&nbsp;查看启动顺序
systemctl show nginx -p After
systemctl show nginx -p Before

#&nbsp;查看完整依赖信息
systemctl show nginx | grep -E "Requires|Wants|After|Before"

9.2 依赖类型说明

| | | | — | — | | 依赖类型 | 说明 | | Requires | 硬依赖,必须成功启动 | | Wants | 软依赖,失败不影响本服务 | | After | 在这些单元之后启动 | | Before | 在这些单元之前启动 | | Conflicts | 冲突关系,不能同时运行 | | BindsTo | 绑定依赖,一起启动停止 |

9.3 修改服务依赖

# 创建覆盖配置目录
sudo systemctl&nbsp;edit&nbsp;nginx

# 或手动创建覆盖文件
sudo&nbsp;mkdir&nbsp;-p&nbsp;/etc/systemd/system/nginx.service.d/
cat&nbsp;> /etc/systemd/system/nginx.service.d/override.conf&nbsp;<<&nbsp;'EOF'
[Unit]
After=mysql.service
Requires=mysql.service
EOF

# 重载配置
sudo systemctl daemon-reload

# 验证依赖
systemctl&nbsp;list-dependencies nginx

9.4 服务启动顺序调试

#&nbsp;分析启动时间
systemd-analyze

#&nbsp;分析各服务启动时间
systemd-analyze blame

#&nbsp;查看启动关键路径
systemd-analyze critical-chain

#&nbsp;查看特定服务启动时间
systemd-analyze critical-chain nginx.service

#&nbsp;生成启动图
systemd-analyze plot > boot.svg

9.5 依赖故障排查

#&nbsp;查看失败依赖
systemctl list-dependencies --failed

#&nbsp;查看服务为何未启动
systemctl status nginx

#&nbsp;查看启动日志
journalctl -u nginx -b

#&nbsp;检查循环依赖
systemd-analyze verify /etc/systemd/system/nginx.service

#&nbsp;验证单元文件
systemd-analyze verify /etc/systemd/system/*.service

十、服务日志查看

10.1 journalctl 基础

#&nbsp;查看所有日志
journalctl

#&nbsp;查看特定服务日志
journalctl -u nginx

#&nbsp;实时跟踪日志
journalctl -u nginx -f

#&nbsp;查看最近 N 行
journalctl -u nginx -n 100

#&nbsp;查看最近日志
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx --since "2024-01-15 10:00:00"
journalctl -u nginx --until "2024-01-15 12:00:00"

#&nbsp;查看特定优先级日志
journalctl -u nginx -p err
journalctl -u nginx -p warning
journalctl -u nginx -p info

#&nbsp;查看本次启动日志
journalctl -u nginx -b

#&nbsp;查看上次启动日志
journalctl -u nginx -b -1

10.2 日志过滤

# 按时间过滤
journalctl -u nginx --since today
journalctl -u nginx --since yesterday
journalctl -u nginx --since&nbsp;"10 min ago"

# 按优先级过滤
# 0=emerg, 1=alert, 2=crit, 3=err, 4=warning, 5=notice, 6=info, 7=debug
journalctl -u nginx -p&nbsp;3&nbsp; &nbsp; &nbsp;&nbsp;# 错误及以上
journalctl -u nginx -p err &nbsp; &nbsp;# 错误及以上

# 按字段过滤
journalctl -u nginx _PID=1234
journalctl -u nginx _UID=0
journalctl -u nginx _SYSTEMD_UNIT=nginx.service

# 组合过滤
journalctl -u nginx -p err --since&nbsp;"1 hour ago"

# 搜索关键词
journalctl -u nginx | grep&nbsp;"error"
journalctl -u nginx -g&nbsp;"error"&nbsp; &nbsp;&nbsp;# 内置搜索

10.3 日志输出格式

#&nbsp;简短输出
journalctl -u nginx -o short

#&nbsp;详细输出
journalctl -u nginx -o verbose

#&nbsp;JSON 输出
journalctl -u nginx -o json

#&nbsp;JSON 流式输出
journalctl -u nginx -o json-stream

#&nbsp;导出格式
journalctl -u nginx -o export

#&nbsp;猫格式(类似 cat)
journalctl -u nginx -o cat

#&nbsp;只显示消息
journalctl -u nginx -o cat --no-pager

10.4 日志管理

#&nbsp;查看日志大小
journalctl --disk-usage

#&nbsp;清理日志(保留最近 7 天)
sudo journalctl --vacuum-time=7d

#&nbsp;清理日志(保留 500MB)
sudo journalctl --vacuum-size=500M

#&nbsp;清理日志(保留 1000 个文件)
sudo journalctl --vacuum-files=1000

#&nbsp;立即刷新日志到磁盘
sudo journalctl --flush

#&nbsp;旋转日志
sudo journalctl --rotate

#&nbsp;配置日志保留(/etc/systemd/journald.conf)
cat >> /etc/systemd/journald.conf << EOF
[Journal]
SystemMaxUse=1G
SystemKeepFree=5G
SystemMaxFileSize=100M
MaxRetentionSec=1month
EOF

#&nbsp;重载配置
sudo systemctl restart systemd-journald

10.5 服务日志配置

#&nbsp;在单元文件中配置日志
cat > /etc/systemd/system/nginx.service.d/logging.conf << 'EOF'
[Service]
#&nbsp;标准输出重定向
StandardOutput=journal
StandardError=journal

#&nbsp;日志级别
LogLevelMax=info

#&nbsp;日志速率限制
LogRateLimitIntervalSec=30s
LogRateLimitBurst=1000
EOF

#&nbsp;重载配置
sudo systemctl daemon-reload
sudo systemctl restart nginx

十一、服务资源限制

11.1 CPU 限制

#&nbsp;创建资源限制配置
cat > /etc/systemd/system/nginx.service.d/resources.conf << 'EOF'
[Service]
#&nbsp;CPU 配额(百分比)
CPUQuota=50%

#&nbsp;CPU 权重
CPUWeight=100

#&nbsp;CPU 亲和性
CPUAffinity=0 1

#&nbsp; nice 值
Nice=-5
EOF

#&nbsp;重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx

11.2 内存限制

#&nbsp;创建内存限制配置
cat > /etc/systemd/system/nginx.service.d/memory.conf << 'EOF'
[Service]
#&nbsp;内存限制
MemoryMax=512M
MemoryHigh=400M

#&nbsp;内存交换限制
MemorySwapMax=0

#&nbsp;OOM 分数调整
OOMScoreAdjust=-500
EOF

#&nbsp;重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx

#&nbsp;查看内存使用
systemctl show nginx -p MemoryCurrent
systemctl show nginx -p MemoryMax

11.3 进程和文件限制

#&nbsp;创建限制配置
cat > /etc/systemd/system/nginx.service.d/limits.conf << 'EOF'
[Service]
#&nbsp;最大进程数
TasksMax=100

#&nbsp;最大打开文件数
LimitNOFILE=65535

#&nbsp;最大进程数
LimitNPROC=65535

#&nbsp;核心文件大小
LimitCORE=infinity

#&nbsp;栈大小
LimitSTACK=8M
EOF

#&nbsp;重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx

#&nbsp;查看限制
systemctl show nginx -p LimitNOFILE
systemctl show nginx -p TasksMax

11.4 IO 限制

# 创建 IO 限制配置
cat >&nbsp;/etc/systemd/system/nginx.service.d/io.conf <<&nbsp;'EOF'
[Service]
# IO 权重
IOWeight=100

# 设备 IO 权重
IODeviceWeight=/dev/sda500

# IO 读取限制
IOReadBandwidthMax=/dev/sda50M
IOReadIOPSMax=/dev/sda1000

# IO 写入限制
IOWriteBandwidthMax=/dev/sda50M
IOWriteIOPSMax=/dev/sda1000
EOF

# 重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx

11.5 查看资源使用

#&nbsp;查看服务资源使用
systemctl show nginx -p MemoryCurrent
systemctl show nginx -p CPUUsageNSec
systemctl show nginx -p TasksCurrent

#&nbsp;使用 systemd-cgtop 查看
systemd-cgtop

#&nbsp;使用 systemd-cgls 查看
systemd-cgls /system.slice/nginx.service

#&nbsp;实时监控
watch -n 1 'systemctl show nginx -p MemoryCurrent -p CPUUsageNSec'

十二、定时器服务

12.1 创建定时器

#&nbsp;创建服务文件
cat > /etc/systemd/system/backup.service << 'EOF'
[Unit]
Description=Daily Backup Service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
EOF

#&nbsp;创建定时器文件
cat > /etc/systemd/system/backup.timer << 'EOF'
[Unit]
Description=Run backup daily

[Timer]
#&nbsp;每天凌晨 2 点执行
OnCalendar=*-*-* 02:00:00

#&nbsp;定时器持久化(错过执行时间后补执行)
Persistent=true

#&nbsp;随机延迟(避免同时执行)
RandomizedDelaySec=300

#&nbsp;立即触发一次
OnBootSec=1min

[Install]
WantedBy=timers.target
EOF

#&nbsp;重载配置
sudo systemctl daemon-reload

#&nbsp;启用并启动定时器
sudo systemctl enable --now backup.timer

#&nbsp;验证
systemctl list-timers
systemctl status backup.timer

12.2 定时器时间格式

# OnCalendar 时间格式示例
OnCalendar=daily &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 每天午夜
OnCalendar=weekly &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # 每周一次
OnCalendar=monthly &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 每月一次
OnCalendar=yearly &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # 每年一次
OnCalendar=hourly &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # 每小时
OnCalendar=minutely &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # 每分钟

# 具体时间
OnCalendar=*-*-*&nbsp;02:00:00&nbsp; &nbsp; &nbsp;# 每天&nbsp;2&nbsp;点
OnCalendar=*-*-*&nbsp;02:30:00&nbsp; &nbsp; &nbsp;# 每天&nbsp;2:30
OnCalendar=Mon *-*-*&nbsp;09:00:00&nbsp;# 每周一&nbsp;9&nbsp;点
OnCalendar=*-*-0100:00:00&nbsp; &nbsp; # 每月&nbsp;1&nbsp;号

# 相对时间
OnBootSec=5min &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 启动后&nbsp;5&nbsp;分钟
OnUnitActiveSec=1h &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 上次执行后&nbsp;1&nbsp;小时
OnUnitInactiveSec=1h &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 上次停止后&nbsp;1&nbsp;小时

# 组合使用
OnCalendar=daily
OnBootSec=10min

12.3 定时器管理

#&nbsp;列出所有定时器
systemctl list-timers

#&nbsp;列出所有定时器(包括未激活的)
systemctl list-timers --all

#&nbsp;查看定时器详情
systemctl show backup.timer

#&nbsp;查看下次执行时间
systemctl list-timers | grep backup

#&nbsp;手动触发
sudo systemctl start backup.service

#&nbsp;停止定时器
sudo systemctl stop backup.timer

#&nbsp;禁用定时器
sudo systemctl disable backup.timer

12.4 定时器与 cron 对比

| | | | | — | — | — | | 特性 | systemd timer | cron | | 日志集成 | journalctl | 邮件/文件 | | 依赖管理 | 支持 | 不支持 | | 时间精度 | 秒级 | 分钟级 | | 错过执行 | Persistent | 不补执行 | | 资源控制 | cgroups | 不支持 | | 状态查看 | systemctl | 查看日志 |

十三、目标 (Target) 管理

13.1 查看目标

# 查看当前默认目标
systemctl get-default

# 列出所有目标
systemctl&nbsp;list-units --type=target

# 列出所有目标文件
systemctl&nbsp;list-unit-files --type=target

# 查看目标依赖
systemctl&nbsp;list-dependencies multi-user.target

# 查看当前激活的目标
systemctl&nbsp;list-units --type=target --state=active

13.2 常见目标

| | | | | — | — | — | | 目标 | 说明 | 对应运行级别 | | poweroff.target | 关机 | runlevel 0 | | rescue.target | 救援模式 | runlevel 1 | | multi-user.target | 多用户命令行 | runlevel 3 | | graphical.target | 图形界面 | runlevel 5 | | reboot.target | 重启 | runlevel 6 | | emergency.target | 紧急模式 | – | | shutdown.target | 关机目标 | – | | sleep.target | 睡眠 | – |

13.3 切换目标

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

#&nbsp;切换到图形界面
sudo systemctl isolate graphical.target

#&nbsp;切换到救援模式
sudo systemctl isolate rescue.target

#&nbsp;切换到紧急模式
sudo systemctl isolate emergency.target

#&nbsp;关机
sudo systemctl poweroff

#&nbsp;重启
sudo systemctl reboot

#&nbsp;挂起
sudo systemctl suspend

#&nbsp;休眠
sudo systemctl hibernate

#&nbsp;混合休眠
sudo systemctl hybrid-sleep

13.4 目标依赖配置

#&nbsp;查看目标依赖
systemctl show multi-user.target -p Wants
systemctl show multi-user.target -p Requires

#&nbsp;添加服务到目标
sudo systemctl enable nginx
#&nbsp;这会在 multi-user.target.wants/ 创建链接

#&nbsp;从目标移除服务
sudo systemctl disable nginx

#&nbsp;查看目标下的服务
ls -la /etc/systemd/system/multi-user.target.wants/

十四、服务故障排查

14.1 常见故障及解决

| | | | | | — | — | — | — | | 故障现象 | 可能原因 | 排查命令 | 解决方案 | | 服务无法启动 | 配置错误 | systemctl status | 修正配置 | | 服务启动失败 | 依赖未满足 | systemctl list-dependencies | 启动依赖 | | 服务立即退出 | 程序错误 | journalctl -u 服务 | 修复程序 | | 权限错误 | 用户/组错误 | systemctl show 服务 -p User | 修正权限 | | 端口占用 | 端口冲突 | ss -tulpn | 释放端口 | | 资源不足 | 内存/CPU 限制 | systemd-cgtop | 调整限制 | | 超时 | 启动太慢 | systemctl show -p TimeoutStartUSec | 增加超时 |

14.2 故障排查流程

#!/bin/bash
# 服务故障排查脚本

SERVICE=$1

if&nbsp;[ -z&nbsp;"$SERVICE"&nbsp;];&nbsp;then
&nbsp; &nbsp;&nbsp;echo"用法:$0&nbsp;<服务名>"
&nbsp; &nbsp;&nbsp;exit&nbsp;1
fi

echo"=============================================="
echo" &nbsp;服务故障排查:$SERVICE"
echo"=============================================="

# 1. 检查服务状态
echo&nbsp;-e&nbsp;"\n【1. 服务状态】"
systemctl status&nbsp;$SERVICE&nbsp;--no-pager

# 2. 检查是否启用
echo&nbsp;-e&nbsp;"\n【2. 自启状态】"
systemctl is-enabled&nbsp;$SERVICE

# 3. 检查最近日志
echo&nbsp;-e&nbsp;"\n【3. 最近日志】"
journalctl -u&nbsp;$SERVICE&nbsp;-n 50 --no-pager

# 4. 检查错误日志
echo&nbsp;-e&nbsp;"\n【4. 错误日志】"
journalctl -u&nbsp;$SERVICE&nbsp;-p err --no-pager

# 5. 检查依赖
echo&nbsp;-e&nbsp;"\n【5. 服务依赖】"
systemctl list-dependencies&nbsp;$SERVICE

# 6. 检查进程
echo&nbsp;-e&nbsp;"\n【6. 进程信息】"
systemctl show&nbsp;$SERVICE&nbsp;-p MainPID -p ExecMainPID

# 7. 检查资源使用
echo&nbsp;-e&nbsp;"\n【7. 资源使用】"
systemctl show&nbsp;$SERVICE&nbsp;-p MemoryCurrent -p CPUUsageNSec -p TasksCurrent

# 8. 检查单元文件
echo&nbsp;-e&nbsp;"\n【8. 单元文件】"
systemctl cat&nbsp;$SERVICE

# 9. 检查端口监听
echo&nbsp;-e&nbsp;"\n【9. 端口监听】"
ss -tulpn | grep -E&nbsp;"PID.*$SERVICE|$(systemctl show $SERVICE -p MainPID --value)"

# 10. 验证单元文件
echo&nbsp;-e&nbsp;"\n【10. 单元文件验证】"
systemd-analyze verify $(systemctl show&nbsp;$SERVICE&nbsp;-p FragmentPath --value) 2>&1

14.3 服务启动调试

#&nbsp;启用调试日志
sudo systemctl edit nginx
#&nbsp;添加:
#&nbsp;[Service]
#&nbsp;Environment=NGINX_DEBUG=1

#&nbsp;以调试模式启动
sudo systemctl start nginx --verbose

#&nbsp;查看启动详细日志
journalctl -u nginx -b --no-pager

#&nbsp;检查启动超时
systemctl show nginx -p TimeoutStartUSec

#&nbsp;增加启动超时
sudo systemctl edit nginx
#&nbsp;添加:
#&nbsp;[Service]
#&nbsp;TimeoutStartSec=300

#&nbsp;手动测试启动命令
sudo /usr/sbin/nginx -t

14.4 服务失败恢复

#&nbsp;查看失败服务
systemctl --failed

#&nbsp;重置失败状态
sudo systemctl reset-failed nginx

#&nbsp;重启失败服务
sudo systemctl restart nginx

#&nbsp;配置自动重启
sudo systemctl edit nginx
#&nbsp;添加:
#&nbsp;[Service]
#&nbsp;Restart=on-failure
#&nbsp;RestartSec=10s

#&nbsp;查看重启历史
journalctl -u nginx | grep -i "restart"

14.5 服务性能分析

#&nbsp;分析服务启动时间
systemd-analyze critical-chain nginx.service

#&nbsp;查看服务资源使用
systemd-cgtop

#&nbsp;查看服务进程树
systemd-cgls /system.slice/nginx.service

#&nbsp;生成火焰图(需要 perf)
perf record -g -p $(systemctl show nginx -p MainPID --value)
perf script | stackcollapse-perf.pl | flamegraph.pl > nginx.svg

十五、常见服务配置示例

15.1 Nginx 服务配置

#&nbsp;查看 Nginx 服务状态
systemctl status nginx

#&nbsp;查看单元文件
systemctl cat nginx

#&nbsp;自定义配置
sudo systemctl edit nginx
#&nbsp;添加:
#&nbsp;[Service]
#&nbsp;LimitNOFILE=65535
#&nbsp;CPUQuota=50%
#&nbsp;MemoryMax=512M

#&nbsp;重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx

#&nbsp;验证
systemctl status nginx

15.2 MySQL 服务配置

#&nbsp;查看 MySQL 服务状态
systemctl status mysqld

#&nbsp;查看单元文件
systemctl cat mysqld

#&nbsp;自定义配置
sudo mkdir -p /etc/systemd/system/mysqld.service.d/
cat > /etc/systemd/system/mysqld.service.d/override.conf << 'EOF'
[Service]
LimitNOFILE=65535
MemoryMax=2G
OOMScoreAdjust=-500
EOF

#&nbsp;重载并重启
sudo systemctl daemon-reload
sudo systemctl restart mysqld

15.3 Redis 服务配置

#&nbsp;查看 Redis 服务状态
systemctl status redis

#&nbsp;自定义配置
sudo systemctl edit redis
#&nbsp;添加:
#&nbsp;[Service]
#&nbsp;LimitNOFILE=10000
#&nbsp;MemoryMax=1G
#&nbsp;ExecStart=
#&nbsp;ExecStart=/usr/bin/redis-server /etc/redis.conf

#&nbsp;重载并重启
sudo systemctl daemon-reload
sudo systemctl restart redis

15.4 Docker 服务配置

#&nbsp;查看 Docker 服务状态
systemctl status docker

#&nbsp;自定义配置
sudo systemctl edit docker
#&nbsp;添加:
#&nbsp;[Service]
#&nbsp;ExecStart=
#&nbsp;ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
#&nbsp;LimitNOFILE=infinity
#&nbsp;LimitNPROC=infinity

#&nbsp;重载并重启
sudo systemctl daemon-reload
sudo systemctl restart docker

15.5 自定义应用服务配置

# 完整的服务配置示例
cat&nbsp;> /etc/systemd/system/myapp.service <<&nbsp;'EOF'
[Unit]
Description=My Application Service
Documentation=https://example.com/docs
After=network.target mysql.service redis.service
Requires=mysql.service
Wants=redis.service

[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
EnvironmentFile=/etc/myapp/env
ExecStartPre=/opt/myapp/bin/check-config.sh
ExecStart=/opt/myapp/bin/myapp
ExecReload=/bin/kill -s HUP&nbsp;$MAINPID
ExecStop=/bin/kill -s TERM&nbsp;$MAINPID
Restart=on-failure
RestartSec=10s
TimeoutStartSec=90s
TimeoutStopSec=30s

# 资源限制
LimitNOFILE=65535
LimitNPROC=65535
MemoryMax=1G
CPUQuota=50%

# 安全选项
PrivateTmp=yes
ProtectSystem=full
ProtectHome=yes
NoNewPrivileges=yes
ReadWritePaths=/var/log/myapp /var/data/myapp

# 日志配置
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp

[Install]
WantedBy=multi-user.target
EOF

# 重载并启用
sudo systemctl daemon-reload
sudo systemctl enable --now myapp

十六、自动化脚本

16.1 服务批量管理脚本

#!/bin/bash
#===============================================================================
# 脚本名称:service_manager.sh
# 功能描述:批量管理服务
#===============================================================================

set&nbsp;-e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() {&nbsp;echo&nbsp;-e&nbsp;"${GREEN}[INFO]${NC}&nbsp;$1"; }
log_warn() {&nbsp;echo&nbsp;-e&nbsp;"${YELLOW}[WARN]${NC}&nbsp;$1"; }
log_error() {&nbsp;echo&nbsp;-e&nbsp;"${RED}[ERROR]${NC}&nbsp;$1"; }

# 服务列表
SERVICES=("nginx""mysql""redis""docker")

# 检查服务状态
check_status() {
&nbsp; &nbsp; log_info&nbsp;"检查服务状态..."
&nbsp; &nbsp;&nbsp;for&nbsp;service&nbsp;in"${SERVICES[@]}";&nbsp;do
&nbsp; &nbsp; &nbsp; &nbsp; status=$(systemctl is-active&nbsp;$service&nbsp;2>/dev/null ||&nbsp;echo"inactive")
&nbsp; &nbsp; &nbsp; &nbsp; enabled=$(systemctl is-enabled&nbsp;$service&nbsp;2>/dev/null ||&nbsp;echo"disabled")
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;printf"%-20s %-15s %-15s\n""$service""状态:$status""自启:$enabled"
&nbsp; &nbsp;&nbsp;done
}

# 启动所有服务
start_all() {
&nbsp; &nbsp; log_info&nbsp;"启动所有服务..."
&nbsp; &nbsp;&nbsp;for&nbsp;service&nbsp;in"${SERVICES[@]}";&nbsp;do
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;systemctl start&nbsp;$service&nbsp;2>/dev/null;&nbsp;then
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log_info&nbsp;"$service&nbsp;启动成功"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;else
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log_error&nbsp;"$service&nbsp;启动失败"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;fi
&nbsp; &nbsp;&nbsp;done
}

# 停止所有服务
stop_all() {
&nbsp; &nbsp; log_info&nbsp;"停止所有服务..."
&nbsp; &nbsp;&nbsp;for&nbsp;service&nbsp;in"${SERVICES[@]}";&nbsp;do
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;systemctl stop&nbsp;$service&nbsp;2>/dev/null;&nbsp;then
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log_info&nbsp;"$service&nbsp;停止成功"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;else
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log_error&nbsp;"$service&nbsp;停止失败"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;fi
&nbsp; &nbsp;&nbsp;done
}

# 重启所有服务
restart_all() {
&nbsp; &nbsp; log_info&nbsp;"重启所有服务..."
&nbsp; &nbsp;&nbsp;for&nbsp;service&nbsp;in"${SERVICES[@]}";&nbsp;do
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;systemctl restart&nbsp;$service&nbsp;2>/dev/null;&nbsp;then
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log_info&nbsp;"$service&nbsp;重启成功"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;else
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log_error&nbsp;"$service&nbsp;重启失败"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;fi
&nbsp; &nbsp;&nbsp;done
}

# 启用所有服务
enable_all() {
&nbsp; &nbsp; log_info&nbsp;"启用所有服务自启..."
&nbsp; &nbsp;&nbsp;for&nbsp;service&nbsp;in"${SERVICES[@]}";&nbsp;do
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if&nbsp;systemctl&nbsp;enable$service&nbsp;2>/dev/null;&nbsp;then
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log_info&nbsp;"$service&nbsp;启用自启成功"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;else
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log_error&nbsp;"$service&nbsp;启用自启失败"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;fi
&nbsp; &nbsp;&nbsp;done
}

# 显示帮助
show_help() {
&nbsp; &nbsp;&nbsp;echo"用法:$0&nbsp;[命令]"
&nbsp; &nbsp;&nbsp;echo""
&nbsp; &nbsp;&nbsp;echo"命令:"
&nbsp; &nbsp;&nbsp;echo" &nbsp;status &nbsp; &nbsp;检查服务状态"
&nbsp; &nbsp;&nbsp;echo" &nbsp;start &nbsp; &nbsp; 启动所有服务"
&nbsp; &nbsp;&nbsp;echo" &nbsp;stop &nbsp; &nbsp; &nbsp;停止所有服务"
&nbsp; &nbsp;&nbsp;echo" &nbsp;restart &nbsp; 重启所有服务"
&nbsp; &nbsp;&nbsp;echo" &nbsp;enable &nbsp; &nbsp;启用所有服务自启"
&nbsp; &nbsp;&nbsp;echo" &nbsp;help &nbsp; &nbsp; &nbsp;显示帮助"
}

# 主函数
case"${1:-status}"in
&nbsp; &nbsp; status) &nbsp;check_status ;;
&nbsp; &nbsp; start) &nbsp; start_all ;;
&nbsp; &nbsp; stop) &nbsp; &nbsp;stop_all ;;
&nbsp; &nbsp; restart) restart_all ;;
&nbsp; &nbsp;&nbsp;enable) &nbsp;enable_all ;;
&nbsp; &nbsp;&nbsp;help) &nbsp; &nbsp;show_help ;;
&nbsp; &nbsp; *) &nbsp; &nbsp; &nbsp; log_error&nbsp;"未知命令:$1"; show_help;&nbsp;exit&nbsp;1 ;;
esac

16.2 服务健康检查脚本

#!/bin/bash
#===============================================================================
# 脚本名称:service_health_check.sh
# 功能描述:服务健康检查
#===============================================================================

LOG_FILE="/var/log/service_health.log"
ALERT_EMAIL="[email protected]"

log() {
&nbsp; &nbsp;&nbsp;echo"[$(date '+%Y-%m-%d %H:%M:%S')]&nbsp;$1"&nbsp;| tee -a&nbsp;$LOG_FILE
}

check_service() {
&nbsp; &nbsp;&nbsp;local&nbsp;service=$1
&nbsp; &nbsp;&nbsp;local&nbsp;status=$(systemctl is-active&nbsp;$service&nbsp;2>/dev/null)

&nbsp; &nbsp;&nbsp;if&nbsp;[&nbsp;"$status"&nbsp;!=&nbsp;"active"&nbsp;];&nbsp;then
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;log"⚠️ &nbsp;告警:服务&nbsp;$service&nbsp;状态异常!当前状态:$status"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;echo"服务&nbsp;$service&nbsp;状态异常"&nbsp;| mail -s&nbsp;"服务告警"$ALERT_EMAIL&nbsp;2>/dev/null
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;1
&nbsp; &nbsp;&nbsp;fi

&nbsp; &nbsp;&nbsp;log"✓ 服务&nbsp;$service&nbsp;运行正常"
&nbsp; &nbsp;&nbsp;return&nbsp;0
}

check_port() {
&nbsp; &nbsp;&nbsp;local&nbsp;port=$1
&nbsp; &nbsp;&nbsp;local&nbsp;service=$2

&nbsp; &nbsp;&nbsp;if&nbsp;! ss -tulpn | grep -q&nbsp;":$port&nbsp;";&nbsp;then
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;log"⚠️ &nbsp;告警:端口&nbsp;$port&nbsp;未监听($service)"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;1
&nbsp; &nbsp;&nbsp;fi

&nbsp; &nbsp;&nbsp;log"✓ 端口&nbsp;$port&nbsp;监听正常($service)"
&nbsp; &nbsp;&nbsp;return&nbsp;0
}

check_process() {
&nbsp; &nbsp;&nbsp;local&nbsp;service=$1
&nbsp; &nbsp;&nbsp;local&nbsp;pid=$(systemctl show&nbsp;$service&nbsp;-p MainPID --value)

&nbsp; &nbsp;&nbsp;if&nbsp;[&nbsp;"$pid"&nbsp;==&nbsp;"0"&nbsp;] || [ -z&nbsp;"$pid"&nbsp;];&nbsp;then
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;log"⚠️ &nbsp;告警:服务&nbsp;$service&nbsp;无主进程"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;1
&nbsp; &nbsp;&nbsp;fi

&nbsp; &nbsp;&nbsp;if&nbsp;!&nbsp;kill&nbsp;-0&nbsp;$pid&nbsp;2>/dev/null;&nbsp;then
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;log"⚠️ &nbsp;告警:服务&nbsp;$service&nbsp;进程&nbsp;$pid&nbsp;不存在"
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return&nbsp;1
&nbsp; &nbsp;&nbsp;fi

&nbsp; &nbsp;&nbsp;log"✓ 服务&nbsp;$service&nbsp;进程&nbsp;$pid&nbsp;运行正常"
&nbsp; &nbsp;&nbsp;return&nbsp;0
}

# 主检查
log"========== 服务健康检查开始 =========="

# 检查服务状态
check_service nginx
check_service mysql
check_service redis
check_service docker

# 检查端口
check_port 80 nginx
check_port 443 nginx
check_port 3306 mysql
check_port 6379 redis

# 检查进程
check_process nginx
check_process mysql

log&nbsp;"========== 服务健康检查完成 =========="

16.3 服务部署脚本

#!/bin/bash
#===============================================================================
# 脚本名称:service_deploy.sh
# 功能描述:服务部署脚本
#===============================================================================

set&nbsp;-e

SERVICE_NAME=$1
SERVICE_USER=$2
SERVICE_PORT=$3

if&nbsp;[ -z&nbsp;"$SERVICE_NAME"&nbsp;] || [ -z&nbsp;"$SERVICE_USER"&nbsp;];&nbsp;then
&nbsp; &nbsp;&nbsp;echo"用法:$0&nbsp;<服务名> <用户> [端口]"
&nbsp; &nbsp;&nbsp;exit&nbsp;1
fi

echo"部署服务:$SERVICE_NAME"

# 创建用户
if&nbsp;! id&nbsp;$SERVICE_USER&nbsp;&>/dev/null;&nbsp;then
&nbsp; &nbsp; useradd -r -s /sbin/nologin&nbsp;$SERVICE_USER
&nbsp; &nbsp;&nbsp;echo"创建用户:$SERVICE_USER"
fi

# 创建目录
mkdir -p /opt/$SERVICE_NAME
mkdir -p /var/log/$SERVICE_NAME
mkdir -p /etc/$SERVICE_NAME

# 创建服务文件
cat > /etc/systemd/system/$SERVICE_NAME.service << EOF
[Unit]
Description=$SERVICE_NAME&nbsp;Service
After=network.target

[Service]
Type=simple
User=$SERVICE_USER
Group=$SERVICE_USER
WorkingDirectory=/opt/$SERVICE_NAME
ExecStart=/opt/$SERVICE_NAME/bin/$SERVICE_NAME
Restart=on-failure
RestartSec=10s

# 资源限制
LimitNOFILE=65535
MemoryMax=1G

# 安全选项
PrivateTmp=yes
NoNewPrivileges=yes

[Install]
WantedBy=multi-user.target
EOF

# 重载配置
systemctl daemon-reload

# 启用服务
systemctl&nbsp;enable$SERVICE_NAME

echo"服务&nbsp;$SERVICE_NAME&nbsp;部署完成"
echo"启动命令:systemctl start&nbsp;$SERVICE_NAME"
echo&nbsp;"查看状态:systemctl status&nbsp;$SERVICE_NAME"

十七、与旧命令对比

17.1 命令对比表

| | | | | — | — | — | | 功能 | SysV init | systemd | | 启动服务 | service nginx start | systemctl start nginx | | 停止服务 | service nginx stop | systemctl stop nginx | | 重启服务 | service nginx restart | systemctl restart nginx | | 查看状态 | service nginx status | systemctl status nginx | | 启用自启 | chkconfig nginx on | systemctl enable nginx | | 禁用自启 | chkconfig nginx off | systemctl disable nginx | | 查看日志 | tail /var/log/messages | journalctl -u nginx | | 重载配置 | service nginx reload | systemctl reload nginx |

17.2 兼容性

#&nbsp;service 命令仍然可用(兼容模式)
service nginx status
service nginx start
service nginx stop

#&nbsp;chkconfig 命令仍然可用(兼容模式)
chkconfig --list
chkconfig nginx on
chkconfig nginx off

#&nbsp;但推荐使用 systemctl
systemctl status nginx
systemctl enable nginx

17.3 迁移建议

#&nbsp;1. 检查现有 SysV 服务
chkconfig --list

#&nbsp;2. 查看是否有 systemd 单元
systemctl list-unit-files --type=service | grep 服务名

#&nbsp;3. 迁移到 systemd
#&nbsp;- 创建 systemd 单元文件
#&nbsp;- 禁用 SysV 服务
#&nbsp;- 启用 systemd 服务

#&nbsp;4. 验证迁移
systemctl status 服务名

十八、速查表

18.1 常用命令速查

# ========== 服务状态 ==========
systemctl status nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 查看服务状态
systemctl&nbsp;list-units --type=service &nbsp; &nbsp; &nbsp;&nbsp;# 列出所有服务
systemctl&nbsp;list-unit-files --type=service &nbsp;# 列出服务文件
systemctl --failed &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 查看失败服务

# ========== 服务控制 ==========
systemctl start nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 启动服务
systemctl stop nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 停止服务
systemctl restart nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 重启服务
systemctl reload nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 重载配置
systemctl reload-or-restart nginx &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 重载或重启

# ========== 自启管理 ==========
systemctl enable nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 启用自启
systemctl disable nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 禁用自启
systemctl enable --now nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 启用并启动
systemctl is-enabled nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 检查自启状态
systemctl is-active nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 检查运行状态

# ========== 日志查看 ==========
journalctl -u nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 查看服务日志
journalctl -u nginx -f &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 实时跟踪日志
journalctl -u nginx -n&nbsp;100&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 查看最近 100 行
journalctl -u nginx --since&nbsp;"1 hour ago"# 查看 1 小时内日志

# ========== 单元文件 ==========
systemctl cat nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 查看单元文件
systemctl edit nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 编辑单元文件
systemctl daemon-reload &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 重载配置
systemctl show nginx &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 显示单元属性

# ========== 依赖管理 ==========
systemctl&nbsp;list-dependencies nginx &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 查看依赖
systemctl&nbsp;list-dependencies --reverse &nbsp; &nbsp;&nbsp;# 查看反向依赖

# ========== 资源管理 ==========
systemd-cgtop &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 查看资源使用
systemd-cgls &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 查看控制组
systemd-analyze blame &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# 分析启动时间

# ========== 目标管理 ==========
systemctl get-default&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 查看默认目标
systemctl set-default&nbsp;multi-user.target &nbsp;&nbsp;# 设置默认目标
systemctl isolate graphical.target &nbsp; &nbsp; &nbsp; &nbsp;# 切换目标

18.2 快捷别名

# 添加到 ~/.bashrc
alias&nbsp;sc-status='systemctl status'
alias&nbsp;sc-start='systemctl start'
alias&nbsp;sc-stop='systemctl stop'
alias&nbsp;sc-restart='systemctl restart'
alias&nbsp;sc-enable='systemctl enable'
alias&nbsp;sc-disable='systemctl disable'
alias&nbsp;sc-reload='systemctl daemon-reload'
alias&nbsp;sc-failed='systemctl --failed'
alias&nbsp;sc-list='systemctl list-units --type=service'
alias&nbsp;j-nginx='journalctl -u nginx -f'

# 生效
source&nbsp;~/.bashrc

18.3 服务状态代码

# is-active 返回值
0&nbsp;= active &nbsp; &nbsp; &nbsp;# 运行中
1&nbsp;= inactive &nbsp; &nbsp;# 未运行
2&nbsp;= failed &nbsp; &nbsp; &nbsp;# 失败
3&nbsp;= activating &nbsp;# 启动中
4&nbsp;= deactivating # 停止中

# is-enabled 返回值
0&nbsp;= enabled &nbsp; &nbsp; # 已启用
1&nbsp;= disabled &nbsp; &nbsp;# 已禁用
2&nbsp;= static &nbsp; &nbsp; &nbsp;# 静态
3&nbsp;= masked &nbsp; &nbsp; &nbsp;# 已屏蔽

十九、最佳实践

| | | | — | — | | 建议 | 说明 | | 使用 systemctl 而非 service | systemctl 是原生命令 | | 使用 edit 而非直接修改 | 使用 systemctl edit 创建覆盖 | | 配置资源限制 | 防止服务占用过多资源 | | 配置自动重启 | Restart=on-failure | | 配置日志保留 | journalctl –vacuum-time | | 使用定时器替代 cron | systemd timer 更强大 | | 定期检查失败服务 | systemctl –failed | | 记录配置变更 | 维护服务配置文档 | | 测试后再应用 | 在测试环境验证配置 | | 使用配置管理 | Ansible/Puppet 管理服务 |


免责声明:

本文所载程序、技术方法仅面向合法合规的安全研究与教学场景,旨在提升网络安全防护能力,具有明确的技术研究属性。

任何单位或个人未经授权,将本文内容用于攻击、破坏等非法用途的,由此引发的全部法律责任、民事赔偿及连带责任,均由行为人独立承担,本站不承担任何连带责任。

本站内容均为技术交流与知识分享目的发布,若存在版权侵权或其他异议,请通过邮件联系处理,具体联系方式可点击页面上方的联系我

本文转载自:运维星火燎原 刘军军 刘军军《openEuler 欧拉操作系统 – 服务管理类命令超详细使用教程》

CAF目标B——防御网络攻击 网络安全文章

CAF目标B——防御网络攻击

文章总结: 该文档概述了CAF目标B防御网络攻击的框架,旨在保护关键功能的网络与信息系统安全。核心包括六大原则:建立服务保护政策流程、实施身份与访问控制、保障数
评论:0   参与:  0