文章总结: 该文档详细讲解了openEuler系统中systemd服务管理工具systemctl的使用方法。内容涵盖架构解析、单元文件管理、服务启停控制及自启配置等核心操作。通过丰富的命令示例与状态说明表格,系统展示了服务状态监控、依赖管理及故障排查的实战技巧,为运维人员提供了从基础到进阶的标准操作指南,具备极高的实战参考价值。 综合评分: 85 文章分类: 安全运营,实战经验
openEuler 欧拉操作系统 – 服务管理类命令超详细使用教程
原创
刘军军 刘军军
运维星火燎原
2026年2月23日 00:00 山西
目录
- 服务管理简介
- systemd 架构详解
- systemctl 命令基础
- 服务状态管理
- 服务启动/停止/重启
- 开机自启配置
- 服务单元文件详解
- 自定义服务创建
- 服务依赖管理
- 服务日志查看
- 服务资源限制
- 定时器服务
- 目标 (Target) 管理
- 服务故障排查
- 常见服务配置示例
- 自动化脚本
- 与旧命令对比
- 速查表
一、服务管理简介
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 << 'EOF'
#!/bin/bash
echo"MyApp started at $(date)" >> /var/log/myapp.log
whiletrue; do
sleep 60
echo"MyApp running at $(date)" >> /var/log/myapp.log
done
EOF
chmod +x /usr/local/bin/myapp.sh
# 创建服务单元文件
cat > /etc/systemd/system/myapp.service << '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 enable --now myapp
# 验证
systemctl status myapp
8.2 创建带环境变量的服务
# 创建环境变量文件
cat > /etc/myapp/env << 'EOF'
APP_ENV=production
APP_PORT=8080
APP_LOG_LEVEL=info
DB_HOST=localhost
DB_PORT=3306
EOF
# 创建服务单元文件
cat > /etc/systemd/system/myapp.service << '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 << 'EOF'
#!/bin/bash
echo"Running initialization at $(date)" >> /var/log/init-service.log
# 执行初始化任务
mkdir -p /var/data/app
chown app:app /var/data/app
echo"Initialization completed" >> /var/log/init-service.log
EOF
chmod +x /usr/local/bin/init-service.sh
# 创建 oneshot 服务
cat > /etc/systemd/system/init-service.service << '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 enable init-service
8.4 创建带依赖的服务
# 创建主服务
cat > /etc/systemd/system/app.service << '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 << '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 > /etc/systemd/system/[email protected] << 'EOF'
[Unit]
Description=Application Instance %i
After=network.target
[Service]
Type=simple
User=app
ExecStart=/opt/app/bin/app --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 'app@*'
# 停止所有实例
sudo systemctl stop app@{1,2,3}
九、服务依赖管理
9.1 查看服务依赖
# 查看依赖树
systemctl list-dependencies nginx
# 查看反向依赖(哪些服务依赖此服务)
systemctl list-dependencies nginx --reverse
# 查看直接依赖
systemctl show nginx -p Requires
systemctl show nginx -p Wants
# 查看启动顺序
systemctl show nginx -p After
systemctl show nginx -p Before
# 查看完整依赖信息
systemctl show nginx | grep -E "Requires|Wants|After|Before"
9.2 依赖类型说明
| | | | — | — | | 依赖类型 | 说明 | | Requires | 硬依赖,必须成功启动 | | Wants | 软依赖,失败不影响本服务 | | After | 在这些单元之后启动 | | Before | 在这些单元之前启动 | | Conflicts | 冲突关系,不能同时运行 | | BindsTo | 绑定依赖,一起启动停止 |
9.3 修改服务依赖
# 创建覆盖配置目录
sudo systemctl edit nginx
# 或手动创建覆盖文件
sudo mkdir -p /etc/systemd/system/nginx.service.d/
cat > /etc/systemd/system/nginx.service.d/override.conf << 'EOF'
[Unit]
After=mysql.service
Requires=mysql.service
EOF
# 重载配置
sudo systemctl daemon-reload
# 验证依赖
systemctl list-dependencies nginx
9.4 服务启动顺序调试
# 分析启动时间
systemd-analyze
# 分析各服务启动时间
systemd-analyze blame
# 查看启动关键路径
systemd-analyze critical-chain
# 查看特定服务启动时间
systemd-analyze critical-chain nginx.service
# 生成启动图
systemd-analyze plot > boot.svg
9.5 依赖故障排查
# 查看失败依赖
systemctl list-dependencies --failed
# 查看服务为何未启动
systemctl status nginx
# 查看启动日志
journalctl -u nginx -b
# 检查循环依赖
systemd-analyze verify /etc/systemd/system/nginx.service
# 验证单元文件
systemd-analyze verify /etc/systemd/system/*.service
十、服务日志查看
10.1 journalctl 基础
# 查看所有日志
journalctl
# 查看特定服务日志
journalctl -u nginx
# 实时跟踪日志
journalctl -u nginx -f
# 查看最近 N 行
journalctl -u nginx -n 100
# 查看最近日志
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"
# 查看特定优先级日志
journalctl -u nginx -p err
journalctl -u nginx -p warning
journalctl -u nginx -p info
# 查看本次启动日志
journalctl -u nginx -b
# 查看上次启动日志
journalctl -u nginx -b -1
10.2 日志过滤
# 按时间过滤
journalctl -u nginx --since today
journalctl -u nginx --since yesterday
journalctl -u nginx --since "10 min ago"
# 按优先级过滤
# 0=emerg, 1=alert, 2=crit, 3=err, 4=warning, 5=notice, 6=info, 7=debug
journalctl -u nginx -p 3 # 错误及以上
journalctl -u nginx -p err # 错误及以上
# 按字段过滤
journalctl -u nginx _PID=1234
journalctl -u nginx _UID=0
journalctl -u nginx _SYSTEMD_UNIT=nginx.service
# 组合过滤
journalctl -u nginx -p err --since "1 hour ago"
# 搜索关键词
journalctl -u nginx | grep "error"
journalctl -u nginx -g "error" # 内置搜索
10.3 日志输出格式
# 简短输出
journalctl -u nginx -o short
# 详细输出
journalctl -u nginx -o verbose
# JSON 输出
journalctl -u nginx -o json
# JSON 流式输出
journalctl -u nginx -o json-stream
# 导出格式
journalctl -u nginx -o export
# 猫格式(类似 cat)
journalctl -u nginx -o cat
# 只显示消息
journalctl -u nginx -o cat --no-pager
10.4 日志管理
# 查看日志大小
journalctl --disk-usage
# 清理日志(保留最近 7 天)
sudo journalctl --vacuum-time=7d
# 清理日志(保留 500MB)
sudo journalctl --vacuum-size=500M
# 清理日志(保留 1000 个文件)
sudo journalctl --vacuum-files=1000
# 立即刷新日志到磁盘
sudo journalctl --flush
# 旋转日志
sudo journalctl --rotate
# 配置日志保留(/etc/systemd/journald.conf)
cat >> /etc/systemd/journald.conf << EOF
[Journal]
SystemMaxUse=1G
SystemKeepFree=5G
SystemMaxFileSize=100M
MaxRetentionSec=1month
EOF
# 重载配置
sudo systemctl restart systemd-journald
10.5 服务日志配置
# 在单元文件中配置日志
cat > /etc/systemd/system/nginx.service.d/logging.conf << 'EOF'
[Service]
# 标准输出重定向
StandardOutput=journal
StandardError=journal
# 日志级别
LogLevelMax=info
# 日志速率限制
LogRateLimitIntervalSec=30s
LogRateLimitBurst=1000
EOF
# 重载配置
sudo systemctl daemon-reload
sudo systemctl restart nginx
十一、服务资源限制
11.1 CPU 限制
# 创建资源限制配置
cat > /etc/systemd/system/nginx.service.d/resources.conf << 'EOF'
[Service]
# CPU 配额(百分比)
CPUQuota=50%
# CPU 权重
CPUWeight=100
# CPU 亲和性
CPUAffinity=0 1
# nice 值
Nice=-5
EOF
# 重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx
11.2 内存限制
# 创建内存限制配置
cat > /etc/systemd/system/nginx.service.d/memory.conf << 'EOF'
[Service]
# 内存限制
MemoryMax=512M
MemoryHigh=400M
# 内存交换限制
MemorySwapMax=0
# OOM 分数调整
OOMScoreAdjust=-500
EOF
# 重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx
# 查看内存使用
systemctl show nginx -p MemoryCurrent
systemctl show nginx -p MemoryMax
11.3 进程和文件限制
# 创建限制配置
cat > /etc/systemd/system/nginx.service.d/limits.conf << 'EOF'
[Service]
# 最大进程数
TasksMax=100
# 最大打开文件数
LimitNOFILE=65535
# 最大进程数
LimitNPROC=65535
# 核心文件大小
LimitCORE=infinity
# 栈大小
LimitSTACK=8M
EOF
# 重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx
# 查看限制
systemctl show nginx -p LimitNOFILE
systemctl show nginx -p TasksMax
11.4 IO 限制
# 创建 IO 限制配置
cat > /etc/systemd/system/nginx.service.d/io.conf << '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 查看资源使用
# 查看服务资源使用
systemctl show nginx -p MemoryCurrent
systemctl show nginx -p CPUUsageNSec
systemctl show nginx -p TasksCurrent
# 使用 systemd-cgtop 查看
systemd-cgtop
# 使用 systemd-cgls 查看
systemd-cgls /system.slice/nginx.service
# 实时监控
watch -n 1 'systemctl show nginx -p MemoryCurrent -p CPUUsageNSec'
十二、定时器服务
12.1 创建定时器
# 创建服务文件
cat > /etc/systemd/system/backup.service << 'EOF'
[Unit]
Description=Daily Backup Service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
EOF
# 创建定时器文件
cat > /etc/systemd/system/backup.timer << 'EOF'
[Unit]
Description=Run backup daily
[Timer]
# 每天凌晨 2 点执行
OnCalendar=*-*-* 02:00:00
# 定时器持久化(错过执行时间后补执行)
Persistent=true
# 随机延迟(避免同时执行)
RandomizedDelaySec=300
# 立即触发一次
OnBootSec=1min
[Install]
WantedBy=timers.target
EOF
# 重载配置
sudo systemctl daemon-reload
# 启用并启动定时器
sudo systemctl enable --now backup.timer
# 验证
systemctl list-timers
systemctl status backup.timer
12.2 定时器时间格式
# OnCalendar 时间格式示例
OnCalendar=daily # 每天午夜
OnCalendar=weekly # 每周一次
OnCalendar=monthly # 每月一次
OnCalendar=yearly # 每年一次
OnCalendar=hourly # 每小时
OnCalendar=minutely # 每分钟
# 具体时间
OnCalendar=*-*-* 02:00:00 # 每天 2 点
OnCalendar=*-*-* 02:30:00 # 每天 2:30
OnCalendar=Mon *-*-* 09:00:00 # 每周一 9 点
OnCalendar=*-*-0100:00:00 # 每月 1 号
# 相对时间
OnBootSec=5min # 启动后 5 分钟
OnUnitActiveSec=1h # 上次执行后 1 小时
OnUnitInactiveSec=1h # 上次停止后 1 小时
# 组合使用
OnCalendar=daily
OnBootSec=10min
12.3 定时器管理
# 列出所有定时器
systemctl list-timers
# 列出所有定时器(包括未激活的)
systemctl list-timers --all
# 查看定时器详情
systemctl show backup.timer
# 查看下次执行时间
systemctl list-timers | grep backup
# 手动触发
sudo systemctl start backup.service
# 停止定时器
sudo systemctl stop backup.timer
# 禁用定时器
sudo systemctl disable backup.timer
12.4 定时器与 cron 对比
| | | | | — | — | — | | 特性 | systemd timer | cron | | 日志集成 | journalctl | 邮件/文件 | | 依赖管理 | 支持 | 不支持 | | 时间精度 | 秒级 | 分钟级 | | 错过执行 | Persistent | 不补执行 | | 资源控制 | cgroups | 不支持 | | 状态查看 | systemctl | 查看日志 |
十三、目标 (Target) 管理
13.1 查看目标
# 查看当前默认目标
systemctl get-default
# 列出所有目标
systemctl list-units --type=target
# 列出所有目标文件
systemctl list-unit-files --type=target
# 查看目标依赖
systemctl list-dependencies multi-user.target
# 查看当前激活的目标
systemctl 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 切换目标
# 切换到多用户模式
sudo systemctl isolate multi-user.target
# 切换到图形界面
sudo systemctl isolate graphical.target
# 切换到救援模式
sudo systemctl isolate rescue.target
# 切换到紧急模式
sudo systemctl isolate emergency.target
# 关机
sudo systemctl poweroff
# 重启
sudo systemctl reboot
# 挂起
sudo systemctl suspend
# 休眠
sudo systemctl hibernate
# 混合休眠
sudo systemctl hybrid-sleep
13.4 目标依赖配置
# 查看目标依赖
systemctl show multi-user.target -p Wants
systemctl show multi-user.target -p Requires
# 添加服务到目标
sudo systemctl enable nginx
# 这会在 multi-user.target.wants/ 创建链接
# 从目标移除服务
sudo systemctl disable nginx
# 查看目标下的服务
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 [ -z "$SERVICE" ]; then
echo"用法:$0 <服务名>"
exit 1
fi
echo"=============================================="
echo" 服务故障排查:$SERVICE"
echo"=============================================="
# 1. 检查服务状态
echo -e "\n【1. 服务状态】"
systemctl status $SERVICE --no-pager
# 2. 检查是否启用
echo -e "\n【2. 自启状态】"
systemctl is-enabled $SERVICE
# 3. 检查最近日志
echo -e "\n【3. 最近日志】"
journalctl -u $SERVICE -n 50 --no-pager
# 4. 检查错误日志
echo -e "\n【4. 错误日志】"
journalctl -u $SERVICE -p err --no-pager
# 5. 检查依赖
echo -e "\n【5. 服务依赖】"
systemctl list-dependencies $SERVICE
# 6. 检查进程
echo -e "\n【6. 进程信息】"
systemctl show $SERVICE -p MainPID -p ExecMainPID
# 7. 检查资源使用
echo -e "\n【7. 资源使用】"
systemctl show $SERVICE -p MemoryCurrent -p CPUUsageNSec -p TasksCurrent
# 8. 检查单元文件
echo -e "\n【8. 单元文件】"
systemctl cat $SERVICE
# 9. 检查端口监听
echo -e "\n【9. 端口监听】"
ss -tulpn | grep -E "PID.*$SERVICE|$(systemctl show $SERVICE -p MainPID --value)"
# 10. 验证单元文件
echo -e "\n【10. 单元文件验证】"
systemd-analyze verify $(systemctl show $SERVICE -p FragmentPath --value) 2>&1
14.3 服务启动调试
# 启用调试日志
sudo systemctl edit nginx
# 添加:
# [Service]
# Environment=NGINX_DEBUG=1
# 以调试模式启动
sudo systemctl start nginx --verbose
# 查看启动详细日志
journalctl -u nginx -b --no-pager
# 检查启动超时
systemctl show nginx -p TimeoutStartUSec
# 增加启动超时
sudo systemctl edit nginx
# 添加:
# [Service]
# TimeoutStartSec=300
# 手动测试启动命令
sudo /usr/sbin/nginx -t
14.4 服务失败恢复
# 查看失败服务
systemctl --failed
# 重置失败状态
sudo systemctl reset-failed nginx
# 重启失败服务
sudo systemctl restart nginx
# 配置自动重启
sudo systemctl edit nginx
# 添加:
# [Service]
# Restart=on-failure
# RestartSec=10s
# 查看重启历史
journalctl -u nginx | grep -i "restart"
14.5 服务性能分析
# 分析服务启动时间
systemd-analyze critical-chain nginx.service
# 查看服务资源使用
systemd-cgtop
# 查看服务进程树
systemd-cgls /system.slice/nginx.service
# 生成火焰图(需要 perf)
perf record -g -p $(systemctl show nginx -p MainPID --value)
perf script | stackcollapse-perf.pl | flamegraph.pl > nginx.svg
十五、常见服务配置示例
15.1 Nginx 服务配置
# 查看 Nginx 服务状态
systemctl status nginx
# 查看单元文件
systemctl cat nginx
# 自定义配置
sudo systemctl edit nginx
# 添加:
# [Service]
# LimitNOFILE=65535
# CPUQuota=50%
# MemoryMax=512M
# 重载并重启
sudo systemctl daemon-reload
sudo systemctl restart nginx
# 验证
systemctl status nginx
15.2 MySQL 服务配置
# 查看 MySQL 服务状态
systemctl status mysqld
# 查看单元文件
systemctl cat mysqld
# 自定义配置
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
# 重载并重启
sudo systemctl daemon-reload
sudo systemctl restart mysqld
15.3 Redis 服务配置
# 查看 Redis 服务状态
systemctl status redis
# 自定义配置
sudo systemctl edit redis
# 添加:
# [Service]
# LimitNOFILE=10000
# MemoryMax=1G
# ExecStart=
# ExecStart=/usr/bin/redis-server /etc/redis.conf
# 重载并重启
sudo systemctl daemon-reload
sudo systemctl restart redis
15.4 Docker 服务配置
# 查看 Docker 服务状态
systemctl status docker
# 自定义配置
sudo systemctl edit docker
# 添加:
# [Service]
# ExecStart=
# ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
# LimitNOFILE=infinity
# LimitNPROC=infinity
# 重载并重启
sudo systemctl daemon-reload
sudo systemctl restart docker
15.5 自定义应用服务配置
# 完整的服务配置示例
cat > /etc/systemd/system/myapp.service << '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 $MAINPID
ExecStop=/bin/kill -s TERM $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 -e
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
# 服务列表
SERVICES=("nginx""mysql""redis""docker")
# 检查服务状态
check_status() {
log_info "检查服务状态..."
for service in"${SERVICES[@]}"; do
status=$(systemctl is-active $service 2>/dev/null || echo"inactive")
enabled=$(systemctl is-enabled $service 2>/dev/null || echo"disabled")
printf"%-20s %-15s %-15s\n""$service""状态:$status""自启:$enabled"
done
}
# 启动所有服务
start_all() {
log_info "启动所有服务..."
for service in"${SERVICES[@]}"; do
if systemctl start $service 2>/dev/null; then
log_info "$service 启动成功"
else
log_error "$service 启动失败"
fi
done
}
# 停止所有服务
stop_all() {
log_info "停止所有服务..."
for service in"${SERVICES[@]}"; do
if systemctl stop $service 2>/dev/null; then
log_info "$service 停止成功"
else
log_error "$service 停止失败"
fi
done
}
# 重启所有服务
restart_all() {
log_info "重启所有服务..."
for service in"${SERVICES[@]}"; do
if systemctl restart $service 2>/dev/null; then
log_info "$service 重启成功"
else
log_error "$service 重启失败"
fi
done
}
# 启用所有服务
enable_all() {
log_info "启用所有服务自启..."
for service in"${SERVICES[@]}"; do
if systemctl enable$service 2>/dev/null; then
log_info "$service 启用自启成功"
else
log_error "$service 启用自启失败"
fi
done
}
# 显示帮助
show_help() {
echo"用法:$0 [命令]"
echo""
echo"命令:"
echo" status 检查服务状态"
echo" start 启动所有服务"
echo" stop 停止所有服务"
echo" restart 重启所有服务"
echo" enable 启用所有服务自启"
echo" help 显示帮助"
}
# 主函数
case"${1:-status}"in
status) check_status ;;
start) start_all ;;
stop) stop_all ;;
restart) restart_all ;;
enable) enable_all ;;
help) show_help ;;
*) log_error "未知命令:$1"; show_help; exit 1 ;;
esac
16.2 服务健康检查脚本
#!/bin/bash
#===============================================================================
# 脚本名称:service_health_check.sh
# 功能描述:服务健康检查
#===============================================================================
LOG_FILE="/var/log/service_health.log"
ALERT_EMAIL="[email protected]"
log() {
echo"[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a $LOG_FILE
}
check_service() {
local service=$1
local status=$(systemctl is-active $service 2>/dev/null)
if [ "$status" != "active" ]; then
log"⚠️ 告警:服务 $service 状态异常!当前状态:$status"
echo"服务 $service 状态异常" | mail -s "服务告警"$ALERT_EMAIL 2>/dev/null
return 1
fi
log"✓ 服务 $service 运行正常"
return 0
}
check_port() {
local port=$1
local service=$2
if ! ss -tulpn | grep -q ":$port "; then
log"⚠️ 告警:端口 $port 未监听($service)"
return 1
fi
log"✓ 端口 $port 监听正常($service)"
return 0
}
check_process() {
local service=$1
local pid=$(systemctl show $service -p MainPID --value)
if [ "$pid" == "0" ] || [ -z "$pid" ]; then
log"⚠️ 告警:服务 $service 无主进程"
return 1
fi
if ! kill -0 $pid 2>/dev/null; then
log"⚠️ 告警:服务 $service 进程 $pid 不存在"
return 1
fi
log"✓ 服务 $service 进程 $pid 运行正常"
return 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 "========== 服务健康检查完成 =========="
16.3 服务部署脚本
#!/bin/bash
#===============================================================================
# 脚本名称:service_deploy.sh
# 功能描述:服务部署脚本
#===============================================================================
set -e
SERVICE_NAME=$1
SERVICE_USER=$2
SERVICE_PORT=$3
if [ -z "$SERVICE_NAME" ] || [ -z "$SERVICE_USER" ]; then
echo"用法:$0 <服务名> <用户> [端口]"
exit 1
fi
echo"部署服务:$SERVICE_NAME"
# 创建用户
if ! id $SERVICE_USER &>/dev/null; then
useradd -r -s /sbin/nologin $SERVICE_USER
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 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 enable$SERVICE_NAME
echo"服务 $SERVICE_NAME 部署完成"
echo"启动命令:systemctl start $SERVICE_NAME"
echo "查看状态:systemctl status $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 兼容性
# service 命令仍然可用(兼容模式)
service nginx status
service nginx start
service nginx stop
# chkconfig 命令仍然可用(兼容模式)
chkconfig --list
chkconfig nginx on
chkconfig nginx off
# 但推荐使用 systemctl
systemctl status nginx
systemctl enable nginx
17.3 迁移建议
# 1. 检查现有 SysV 服务
chkconfig --list
# 2. 查看是否有 systemd 单元
systemctl list-unit-files --type=service | grep 服务名
# 3. 迁移到 systemd
# - 创建 systemd 单元文件
# - 禁用 SysV 服务
# - 启用 systemd 服务
# 4. 验证迁移
systemctl status 服务名
十八、速查表
18.1 常用命令速查
# ========== 服务状态 ==========
systemctl status nginx # 查看服务状态
systemctl list-units --type=service # 列出所有服务
systemctl list-unit-files --type=service # 列出服务文件
systemctl --failed # 查看失败服务
# ========== 服务控制 ==========
systemctl start nginx # 启动服务
systemctl stop nginx # 停止服务
systemctl restart nginx # 重启服务
systemctl reload nginx # 重载配置
systemctl reload-or-restart nginx # 重载或重启
# ========== 自启管理 ==========
systemctl enable nginx # 启用自启
systemctl disable nginx # 禁用自启
systemctl enable --now nginx # 启用并启动
systemctl is-enabled nginx # 检查自启状态
systemctl is-active nginx # 检查运行状态
# ========== 日志查看 ==========
journalctl -u nginx # 查看服务日志
journalctl -u nginx -f # 实时跟踪日志
journalctl -u nginx -n 100 # 查看最近 100 行
journalctl -u nginx --since "1 hour ago"# 查看 1 小时内日志
# ========== 单元文件 ==========
systemctl cat nginx # 查看单元文件
systemctl edit nginx # 编辑单元文件
systemctl daemon-reload # 重载配置
systemctl show nginx # 显示单元属性
# ========== 依赖管理 ==========
systemctl list-dependencies nginx # 查看依赖
systemctl list-dependencies --reverse # 查看反向依赖
# ========== 资源管理 ==========
systemd-cgtop # 查看资源使用
systemd-cgls # 查看控制组
systemd-analyze blame # 分析启动时间
# ========== 目标管理 ==========
systemctl get-default # 查看默认目标
systemctl set-default multi-user.target # 设置默认目标
systemctl isolate graphical.target # 切换目标
18.2 快捷别名
# 添加到 ~/.bashrc
alias sc-status='systemctl status'
alias sc-start='systemctl start'
alias sc-stop='systemctl stop'
alias sc-restart='systemctl restart'
alias sc-enable='systemctl enable'
alias sc-disable='systemctl disable'
alias sc-reload='systemctl daemon-reload'
alias sc-failed='systemctl --failed'
alias sc-list='systemctl list-units --type=service'
alias j-nginx='journalctl -u nginx -f'
# 生效
source ~/.bashrc
18.3 服务状态代码
# is-active 返回值
0 = active # 运行中
1 = inactive # 未运行
2 = failed # 失败
3 = activating # 启动中
4 = deactivating # 停止中
# is-enabled 返回值
0 = enabled # 已启用
1 = disabled # 已禁用
2 = static # 静态
3 = masked # 已屏蔽
十九、最佳实践
| | | | — | — | | 建议 | 说明 | | 使用 systemctl 而非 service | systemctl 是原生命令 | | 使用 edit 而非直接修改 | 使用 systemctl edit 创建覆盖 | | 配置资源限制 | 防止服务占用过多资源 | | 配置自动重启 | Restart=on-failure | | 配置日志保留 | journalctl –vacuum-time | | 使用定时器替代 cron | systemd timer 更强大 | | 定期检查失败服务 | systemctl –failed | | 记录配置变更 | 维护服务配置文档 | | 测试后再应用 | 在测试环境验证配置 | | 使用配置管理 | Ansible/Puppet 管理服务 |
免责声明:
本文所载程序、技术方法仅面向合法合规的安全研究与教学场景,旨在提升网络安全防护能力,具有明确的技术研究属性。
任何单位或个人未经授权,将本文内容用于攻击、破坏等非法用途的,由此引发的全部法律责任、民事赔偿及连带责任,均由行为人独立承担,本站不承担任何连带责任。
本站内容均为技术交流与知识分享目的发布,若存在版权侵权或其他异议,请通过邮件联系处理,具体联系方式可点击页面上方的联系我。
本文转载自:运维星火燎原 刘军军 刘军军《openEuler 欧拉操作系统 – 服务管理类命令超详细使用教程》
版权声明
本站仅做备份收录,仅供研究与教学参考之用。
读者将信息用于其他用途的,全部法律及连带责任由读者自行承担,本站不承担任何责任。









评论