HIGH_FREQUENCY_MODE

NextBlog
NEXT.

下一个博客,记录精彩生活

LIVE_STREAM_CONNECTED

Systemd 服务管理指南

A

Mastermind

admin

Dimension

Linux

Timestamp

2025年12月21日

Systemd 是现代 Linux 系统的初始化系统和服务管理器,用于管理系统服务、启动流程和日志。

基础命令

服务管理

# 启动服务
sudo systemctl start nginx

# 停止服务
sudo systemctl stop nginx

# 重启服务
sudo systemctl restart nginx

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

# 查看状态
sudo systemctl status nginx

# 开机自启
sudo systemctl enable nginx

# 禁用开机自启
sudo systemctl disable nginx

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

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

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

# 检查是否运行
sudo systemctl is-active nginx

查看服务

# 列出所有服务
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 nginx

创建自定义服务

服务文件位置

  • 系统服务:/etc/systemd/system/
  • 软件包服务:/usr/lib/systemd/system/

基础服务模板

创建 /etc/systemd/system/myapp.service

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

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/node /var/www/myapp/app.js
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

完整服务示例

[Unit]
Description=My Node.js Application
Documentation=https://example.com/docs
After=network.target mongodb.service
Requires=mongodb.service

[Service]
Type=simple
User=deploy
Group=deploy
WorkingDirectory=/var/www/myapp

# 环境变量
Environment=NODE_ENV=production
Environment=PORT=3000
EnvironmentFile=/var/www/myapp/.env

# 启动命令
ExecStart=/usr/bin/node app.js
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID

# 重启策略
Restart=always
RestartSec=10
StartLimitInterval=60
StartLimitBurst=3

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

# 安全设置
NoNewPrivileges=true
PrivateTmp=true

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

[Install]
WantedBy=multi-user.target

启用服务

# 重载 systemd 配置
sudo systemctl daemon-reload

# 启用并启动
sudo systemctl enable --now myapp

# 查看状态
sudo systemctl status myapp

服务类型

[Service]
# simple - 默认,ExecStart 进程为主进程
Type=simple

# forking - 进程 fork 后父进程退出
Type=forking
PIDFile=/var/run/myapp.pid

# oneshot - 一次性任务
Type=oneshot
RemainAfterExit=yes

# notify - 服务启动后发送通知
Type=notify

# idle - 等待其他任务完成后启动
Type=idle

重启策略

[Service]
# 重启条件
Restart=no              # 不重启
Restart=on-success      # 正常退出时重启
Restart=on-failure      # 异常退出时重启
Restart=on-abnormal     # 信号终止或超时时重启
Restart=on-abort        # 信号终止时重启
Restart=always          # 总是重启

# 重启间隔
RestartSec=10

# 限制重启频率
StartLimitInterval=60   # 60秒内
StartLimitBurst=3       # 最多重启3次

定时器 (Timer)

替代 cron 的定时任务。

创建定时器

/etc/systemd/system/backup.timer

[Unit]
Description=Daily Backup Timer

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target

/etc/systemd/system/backup.service

[Unit]
Description=Backup Service

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

定时器语法

# 每天凌晨3点
OnCalendar=*-*-* 03:00:00

# 每周一凌晨
OnCalendar=Mon *-*-* 00:00:00

# 每月1号
OnCalendar=*-*-01 00:00:00

# 每小时
OnCalendar=hourly

# 每天
OnCalendar=daily

# 启动后延迟
OnBootSec=5min

# 上次执行后间隔
OnUnitActiveSec=1h

管理定时器

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

# 查看定时器
systemctl list-timers

# 手动触发
sudo systemctl start backup.service

日志管理

journalctl

# 查看服务日志
journalctl -u nginx

# 实时追踪
journalctl -u nginx -f

# 最近100行
journalctl -u nginx -n 100

# 今天的日志
journalctl -u nginx --since today

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

# 错误级别
journalctl -u nginx -p err

# 输出格式
journalctl -u nginx -o json
journalctl -u nginx -o json-pretty

# 查看启动日志
journalctl -b

# 磁盘占用
journalctl --disk-usage

# 清理日志
sudo journalctl --vacuum-time=7d
sudo journalctl --vacuum-size=500M

系统管理

# 重启系统
sudo systemctl reboot

# 关机
sudo systemctl poweroff

# 挂起
sudo systemctl suspend

# 休眠
sudo systemctl hibernate

# 进入救援模式
sudo systemctl rescue

# 查看启动耗时
systemd-analyze
systemd-analyze blame
systemd-analyze critical-chain

常用服务配置

Node.js 应用

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

[Service]
Type=simple
User=node
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/node app.js
Restart=on-failure
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

Python 应用

[Unit]
Description=Python App
After=network.target

[Service]
Type=simple
User=python
WorkingDirectory=/var/www/app
ExecStart=/var/www/app/venv/bin/python app.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

Go 应用

[Unit]
Description=Go App
After=network.target

[Service]
Type=simple
User=go
ExecStart=/usr/local/bin/myapp
Restart=on-failure
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target

故障排查

# 查看服务详情
systemctl show nginx

# 查看失败原因
systemctl status nginx
journalctl -xe

# 验证服务文件
systemd-analyze verify /etc/systemd/system/myapp.service

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

常见问题

服务启动失败

  1. 检查 systemctl status 输出
  2. 查看 journalctl -u service -n 50
  3. 验证 ExecStart 路径和权限
  4. 检查用户和工作目录

配置不生效

sudo systemctl daemon-reload
sudo systemctl restart service

总结

Systemd 核心功能:

  • 服务生命周期管理
  • 依赖关系处理
  • 自动重启和资源限制
  • 定时任务(Timer)
  • 统一日志管理(Journal)

掌握 systemd 是 Linux 运维的基础技能。

评论

加载评论中...
Spirit Sync

"正在同步你的多巴胺频率,建立高维链接..."