系统服务 #

一、systemd 基础 #

1.1 systemd 概述 #

systemd 是 Linux 系统的初始化系统和服务管理器,取代了传统的 SysV init。

主要组件:

  • systemd:主进程
  • systemctl:命令行管理工具
  • journald:日志管理
  • systemd-timer:定时任务

1.2 systemctl 基本用法 #

bash
# 查看服务状态
systemctl status nginx
systemctl status sshd

# 启动服务
sudo systemctl start nginx

# 停止服务
sudo systemctl stop nginx

# 重启服务
sudo systemctl restart nginx

# 重新加载配置
sudo systemctl reload nginx

# 查看服务是否运行
systemctl is-active nginx
systemctl is-enabled nginx

# 查看所有服务
systemctl list-units --type=service
systemctl list-units --type=service --all

1.3 服务管理 #

bash
# 开机自启
sudo systemctl enable nginx

# 禁用开机自启
sudo systemctl disable nginx

# 查看服务依赖
systemctl list-dependencies nginx

# 查看反向依赖
systemctl list-dependencies --reverse nginx

# 查看服务文件位置
systemctl show nginx | grep FragmentPath

二、服务配置文件 #

2.1 服务文件结构 #

ini
[Unit]
Description=nginx
After=network.target

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

[Install]
WantedBy=multi-user.target

2.2 服务类型 #

ini
# Type=simple     - 默认,前台运行
# Type=forking    - 后台运行,需要 PID 文件
# Type=oneshot    - 一次性任务
# Type=notify     - 启动完成通知
# Type=dbus       - 通过 D-Bus 通知

2.3 服务管理示例 #

bash
# 创建服务文件
sudo vim /etc/systemd/system/myapp.service

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

[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/myapp/app.py
WorkingDirectory=/opt/myapp
Restart=always
RestartSec=10
User=www-data
Group=www-data
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target

# 重载 systemd
sudo systemctl daemon-reload

# 启动服务
sudo systemctl start myapp

# 设置开机自启
sudo systemctl enable myapp

2.4 资源限制 #

ini
[Service]
# 内存限制
MemoryMax=1G
MemoryHigh=512M

# CPU 限制
CPUQuota=50%

# 文件描述符限制
LimitNOFILE=65535

# 进程数限制
TasksMax=100

三、日志管理 #

3.1 journalctl 基本用法 #

bash
# 查看所有日志
journalctl

# 查看实时日志
journalctl -f

# 查看指定服务日志
journalctl -u nginx
journalctl -u nginx -u mysql

# 按时间过滤
journalctl --since "2024-01-01"
journalctl --until "2024-01-02"
journalctl --since "1 hour ago"

# 按优先级过滤
journalctl -p err
journalctl -p warning..emerg

# 查看最近日志
journalctl -n 100

# 查看磁盘使用
journalctl --disk-usage

3.2 日志配置 #

bash
# 查看日志配置
cat /etc/systemd/journald.conf

# 配置示例
[Journal]
SystemMaxUse=500M
SystemMaxFileSize=50M
MaxRetentionSec=30day
ForwardToSyslog=yes

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

3.3 日志分析 #

bash
# 按服务统计
journalctl -u nginx --no-pager | wc -l

# 按错误统计
journalctl -p err -b

# 按时间段统计
journalctl --since "2024-01-01" --until "2024-01-02"

# 导出日志
journalctl -u nginx > nginx.log

四、定时任务 #

4.1 systemd.timer #

bash
# 创建定时器服务
sudo vim /etc/systemd/system/mytask.service

[Unit]
Description=My Scheduled Task

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

# 创建定时器
sudo vim /etc/systemd/system/mytask.timer

[Unit]
Description=Run mytask daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

# 启用定时器
sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer

# 查看定时器状态
systemctl list-timers

4.2 定时器语法 #

ini
# 常用定时器配置
OnCalendar=daily         # 每天
OnCalendar=weekly       # 每周
OnCalendar=monthly      # 每月
OnCalendar=hourly       # 每小时
OnCalendar=*:0/5        # 每5分钟

# 具体时间
OnCalendar=2024-01-01 00:00:00
OnCalendar=Mon *-*-* 02:00:00  # 每周一凌晨2点

# 范围
OnCalendar=Sat,Sun 10:00:00     # 周末10点

4.3 crontab 对比 #

特性 crontab systemd.timer
精度 分钟
日志 独立 journald
依赖 简单 灵活
持久

五、实战示例 #

5.1 Nginx 服务配置 #

bash
# 创建服务文件
sudo vim /etc/systemd/system/nginx.service

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.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
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

# 启用服务
sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx

5.2 Node.js 应用服务 #

bash
sudo vim /etc/systemd/system/nodeapp.service

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

[Service]
Type=simple
User=nodejs
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/server.js
Restart=always
RestartSec=10
Environment=NODE_ENV=production
Environment=PORT=3000

# 安全限制
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadOnlyPaths=/opt/myapp
PrivateTmp=true

[Install]
WantedBy=multi-user.target

5.3 备份定时任务 #

bash
# 创建备份脚本
sudo vim /usr/local/bin/backup.sh

#!/bin/bash
DATE=$(date +%Y%m%d)
BACKUP_DIR="/backup"
SOURCE_DIR="/var/www/html"

mkdir -p $BACKUP_DIR
tar -czf $BACKUP_DIR/backup_$DATE.tar.gz $SOURCE_DIR
find $BACKUP_DIR -name "*.tar.gz" -mtime +30 -delete

# 创建服务
sudo vim /etc/systemd/system/backup.service

[Unit]
Description=Backup Service

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

# 创建定时器
sudo vim /etc/systemd/system/backup.timer

[Unit]
Description=Run backup daily at 2am

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

[Install]
WantedBy=timers.target

# 启用
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer

六、服务故障排查 #

6.1 查看日志 #

bash
# 查看服务启动失败原因
journalctl -xe
journalctl -u nginx --no-pager -b

# 查看错误日志
journalctl -p err -b

# 持续跟踪
journalctl -u nginx -f

6.2 调试服务 #

bash
# 查看服务详细状态
systemctl status nginx -l

# 查看启动过程
systemctl show nginx

# 检查依赖
systemctl list-dependencies nginx --all

# 测试服务启动
sudo systemctl start nginx

6.3 常见问题 #

bash
# 服务启动失败
# 1. 检查配置文件
nginx -t

# 2. 检查端口占用
sudo lsof -i :80

# 3. 检查权限
ls -la /var/run/nginx.pid

# 4. 查看详细日志
journalctl -u nginx -n 50

七、小结 #

本章学习了 Linux 系统服务管理的核心内容,包括 systemd、服务配置、日志管理和定时任务。

关键要点:

  1. systemctl 是管理服务的主要工具
  2. 服务配置文件采用 INI 格式
  3. journalctl 是日志查看的主要工具
  4. systemd.timer 提供精确的定时任务
  5. 正确配置服务依赖和资源限制

下一章预告: 日志管理 - 学习系统日志管理和分析技术。

最后更新:2026-03-27