Get the FREE Ultimate OpenClaw Setup Guide →
npx machina-cli add skill chaterm/terminal-skills/systemd --openclaw
Files (1)
SKILL.md
5.6 KB

Systemd 服务管理

概述

Systemd 服务单元编写、依赖管理、日志查看等技能。

服务管理

基础命令

# 启停服务
systemctl start service-name
systemctl stop service-name
systemctl restart service-name
systemctl reload service-name       # 重载配置(不中断服务)

# 开机启动
systemctl enable service-name
systemctl disable service-name
systemctl enable --now service-name # 启用并立即启动

# 查看状态
systemctl status service-name
systemctl is-active service-name
systemctl is-enabled service-name
systemctl is-failed service-name

服务列表

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

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

# 查看依赖
systemctl list-dependencies service-name
systemctl list-dependencies --reverse service-name

单元文件

文件位置

# 系统单元(包管理器安装)
/usr/lib/systemd/system/

# 管理员自定义
/etc/systemd/system/

# 运行时生成
/run/systemd/system/

# 优先级:/etc > /run > /usr/lib

基础服务单元

# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
Documentation=https://example.com/docs
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=appuser
Group=appgroup
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/start.sh
ExecStop=/opt/myapp/bin/stop.sh
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

服务类型

# simple(默认)- 主进程即服务进程
Type=simple
ExecStart=/usr/bin/myapp

# forking - 传统守护进程
Type=forking
PIDFile=/var/run/myapp.pid
ExecStart=/usr/bin/myapp -d

# oneshot - 一次性任务
Type=oneshot
ExecStart=/usr/bin/backup.sh
RemainAfterExit=yes

# notify - 服务就绪通知
Type=notify
ExecStart=/usr/bin/myapp

环境变量

[Service]
# 直接设置
Environment="VAR1=value1" "VAR2=value2"

# 从文件加载
EnvironmentFile=/etc/myapp/env
EnvironmentFile=-/etc/myapp/env.local  # - 表示可选

# 传递给子进程
PassEnvironment=HOME USER

资源限制

[Service]
# 文件描述符
LimitNOFILE=65535

# 进程数
LimitNPROC=4096

# 内存限制
MemoryLimit=512M
MemoryMax=1G

# CPU 限制
CPUQuota=50%

# 超时设置
TimeoutStartSec=30
TimeoutStopSec=30

安全选项

[Service]
# 用户隔离
User=appuser
Group=appgroup
DynamicUser=yes

# 文件系统保护
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/myapp

# 网络隔离
PrivateNetwork=yes

# 能力限制
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=yes

日志管理

journalctl

# 查看服务日志
journalctl -u service-name
journalctl -u service-name -f       # 实时跟踪
journalctl -u service-name --since today
journalctl -u service-name --since "1 hour ago"
journalctl -u service-name -n 100   # 最后100行

# 按时间范围
journalctl --since "2024-01-01" --until "2024-01-02"

# 按优先级
journalctl -p err                   # 错误及以上
journalctl -p warning

# 输出格式
journalctl -u service-name -o json
journalctl -u service-name -o json-pretty

# 磁盘使用
journalctl --disk-usage
journalctl --vacuum-size=500M       # 清理到500M
journalctl --vacuum-time=7d         # 保留7天

定时器

Timer 单元

# /etc/systemd/system/backup.timer
[Unit]
Description=Daily Backup Timer

[Timer]
OnCalendar=daily
OnCalendar=*-*-* 02:00:00           # 每天凌晨2点
Persistent=true                      # 错过的任务补执行

[Install]
WantedBy=timers.target
# /etc/systemd/system/backup.service
[Unit]
Description=Backup Service

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

定时器管理

# 启用定时器
systemctl enable --now backup.timer

# 查看定时器
systemctl list-timers
systemctl list-timers --all

常见场景

场景 1:Node.js 应用

[Unit]
Description=Node.js Application
After=network.target

[Service]
Type=simple
User=node
WorkingDirectory=/opt/nodeapp
ExecStart=/usr/bin/node /opt/nodeapp/app.js
Restart=on-failure
RestartSec=10
Environment=NODE_ENV=production
Environment=PORT=3000

[Install]
WantedBy=multi-user.target

场景 2:Java 应用

[Unit]
Description=Java Application
After=network.target

[Service]
Type=simple
User=java
ExecStart=/usr/bin/java -Xms512m -Xmx1024m -jar /opt/app/app.jar
SuccessExitStatus=143
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

场景 3:覆盖系统服务配置

# 创建覆盖目录
systemctl edit nginx

# 或手动创建
mkdir -p /etc/systemd/system/nginx.service.d/
cat > /etc/systemd/system/nginx.service.d/override.conf << EOF
[Service]
LimitNOFILE=65535
EOF

systemctl daemon-reload
systemctl restart nginx

故障排查

问题排查方法
服务启动失败systemctl status, journalctl -u
依赖问题systemctl list-dependencies
配置错误systemd-analyze verify service.service
权限问题检查 User/Group、文件权限
超时调整 TimeoutStartSec
# 重载配置
systemctl daemon-reload

# 分析启动时间
systemd-analyze
systemd-analyze blame
systemd-analyze critical-chain

# 验证单元文件
systemd-analyze verify /etc/systemd/system/myapp.service

Source

git clone https://github.com/chaterm/terminal-skills/blob/main/server/systemd/SKILL.mdView on GitHub

Overview

你可以使用 systemd 编写和管理服务单元,处理服务依赖、开机自启、资源与安全限制,并通过 journalctl 进行集中日志查看。此技能覆盖基础命令、单元文件结构、环境与定时任务、以及故障排查等,帮助你在服务器上实现高可用、可观测的服务。

How This Skill Works

systemd 以单位(unit)来描述不同对象(如 service、timer、slice 等),systemctl 提供对这些单位的启动、停止、重载、状态查询等操作。你通过编辑 /etc/systemd/system/ 等目录下的单元文件定义服务的行为,运行 daemon-reload 以应用改动,并使用 systemctl enable/disable 实现开机自启。日志由 journalctl 集中收集,定时任务由 timer 单元触发。

When to Use It

  • 需要将应用作为长期运行的服务并实现开机自启
  • 需要统一的进程监控、重启策略与日志聚合
  • 需要对资源(内存、CPU、文件描述符等)和安全性进行严格控制
  • 需要以定时任务形式执行计划性工作(而非仅靠 cron)
  • 需要对现有服务进行快速覆盖、覆盖配置或逐步演进的部署

Quick Start

  1. 创建一个基础服务单元 /etc/systemd/system/myapp.service,定义 Description、After、ExecStart 等
  2. 执行 systemctl daemon-reload 以加载新单元
  3. 启用并立即启动服务:systemctl enable --now myapp.service
  4. 查看状态与日志:systemctl status myapp.service;journalctl -u myapp.service -f

Best Practices

  • 优先使用 drop-in 覆盖(systemctl edit)而非直接修改主单元文件,便于维护和回滚
  • 通过 EnvironmentFile 和 PassEnvironment 管理环境变量,确保环境的可移植性与安全性
  • 结合 Restart、RestartSec 与 TimeoutStartSec 设定可靠的重启策略与启动超时
  • 为服务设置资源限制(MemoryLimit、CPUQuota、LimitNOFILE)与安全选项(PrivateNetwork、ProtectSystem、NoNewPrivileges)以提升稳定性与隔离性
  • 使用 Type 根据应用特性选择:长期运行的(simple 或 notify) vs 一次性任务(oneshot),并在合适场景结合 ExecReload
  • 利用 systemd-analyze 及 verify 进行性能分析与单元文件校验,确保部署前的正确性

Example Use Cases

  • 场景 1:Node.js 应用的服务化部署,配置 User、WorkingDirectory、环境变量及端口,确保崩溃后自动重启
  • 场景 2:Java 应用的服务化部署,设置内存参数、ExitStatus 及重启策略,确保在系统重启后快速恢复
  • 场景 3:通过 systemctl edit 或覆盖目录为 nginx 等系统服务增加自定义的资源限制(如 LimitNOFILE)
  • 场景 4:使用 backup.timer + backup.service 设置每日定时备份,确保任务在计划时间执行且错过的任务会在下次触发时补执行
  • 场景 5:使用 PrivateNetwork、ProtectSystem、ReadWritePaths 等安全选项对关键服务进行隔离与保护

Frequently Asked Questions

Add this skill to your agents

Related Skills

Sponsor this space

Reach thousands of developers