Linux systemd 服务管理完全指南

Linux systemd 服务管理完全指南

Someone Lv5

systemd 是当今绝大多数 Linux 发行版默认的 init 系统和服务管理器。它取代了传统的 SysV init,提供了更快的启动速度、更清晰的依赖管理和更强大的日志系统。本文将全面介绍 systemd 的核心概念和日常使用技巧。

一、systemd 核心概念

1.1 什么是 Unit

systemd 将系统中的一切资源抽象为 Unit(单元)。每个 Unit 由一个配置文件定义,常见的 Unit 类型包括:

Unit 类型文件后缀作用
Service.service守护进程/后台服务
Socket.socket进程间通信套接字
Target.target启动目标/运行级别
Timer.timer定时任务(替代 cron)
Mount.mount文件系统挂载点
Path.path文件或目录路径监控

1.2 Unit 配置文件路径

systemd 按以下优先级加载 Unit 配置:

  1. /etc/systemd/system/ —— 管理员自定义(优先级最高)
  2. /run/systemd/system/ —— 运行时配置
  3. /usr/lib/systemd/system/ —— 软件包安装的默认配置

日常操作中,自定义服务文件应放在 /etc/systemd/system/ 目录下。

二、systemctl 命令详解

systemctl 是管理 systemd 服务的主要命令。

2.1 服务生命周期管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 启动服务
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 is-active nginx

# 查看服务是否已启用开机自启
sudo systemctl is-enabled nginx

2.2 Unit 列表查看

1
2
3
4
5
6
7
8
9
10
11
12
# 列出所有运行中的服务
systemctl list-units --type=service --state=running

# 列出所有已安装的服务
systemctl list-unit-files --type=service

# 列出所有失败的 Unit
systemctl --failed

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

2.3 依赖关系管理

1
2
3
4
5
6
7
8
9
10
11
# 查看某个服务的依赖
systemctl list-dependencies nginx

# 查看哪些服务依赖于本服务
systemctl list-dependencies --reverse nginx

# 屏蔽服务(防止手动或依赖启动)
sudo systemctl mask nginx

# 取消屏蔽
sudo systemctl unmask nginx

三、编写自定义 Service Unit

创建一个名为 myapp.service 的服务文件,放在 /etc/systemd/system/ 下。

3.1 基本结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Unit]
Description=My Application Service
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
ExecStart=/usr/local/bin/myapp --config /etc/myapp/config.yml
Restart=on-failure
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

3.2 关键字段解析

[Unit] 部分

字段 说明
Description 服务的描述信息
After 在哪些 Unit 之后启动(不强制依赖)
Requires 强依赖,依赖的 Unit 启动失败时本服务不启动
Wants 弱依赖,依赖的 Unit 启动失败不影响本服务
Before 在哪些 Unit 之前启动

[Service] 部分

字段 说明
Type 启动类型:simpleforkingoneshotnotify
ExecStart 启动命令(绝对路径)
ExecStop 停止命令
ExecReload 重载命令
Restart 重启策略:noon-successon-failurealways
RestartSec 重启间隔秒数
User / Group 运行服务的用户和组

Type 的选择

  • simple(默认):主进程直接在前台运行,systemd 认为服务已启动
  • forking:进程 fork 后父进程退出,子进程继续运行(适用于传统 daemon)
  • oneshot:执行一次即退出,常用于初始化任务
  • notify:进程启动后通过 sd_notify() 通知 systemd
  • dbus:进程在 D-Bus 上注册后才认为启动完成

3.3 完整示例:Node.js Web 应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[Unit]
Description=Node.js Web Application
After=network.target mysql.service
Wants=mysql.service

[Service]
Type=simple
User=nodeapp
Group=nodeapp
WorkingDirectory=/var/www/myapp
Environment=NODE_ENV=production
Environment=PORT=3000
ExecStart=/usr/bin/node /var/www/myapp/app.js
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp-node
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

应用服务文件后执行:

1
2
3
sudo systemctl daemon-reload    # 重载配置
sudo systemctl enable myapp # 设置开机自启
sudo systemctl start myapp # 启动服务

四、日志查看 —— journalctl

systemd 的日志系统 journald 统一管理所有服务日志。

4.1 基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 查看所有日志
journalctl

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

# 实时跟踪日志(类似 tail -f)
journalctl -u nginx -f

# 查看最近 10 条日志
journalctl -u nginx -n 10

# 查看最近 30 分钟的日志
journalctl --since "30 min ago"

# 查看从某个时间点开始的日志
journalctl --since "2026-06-06 00:00:00" --until "2026-06-07 00:00:00"

# 按优先级过滤
journalctl -u nginx -p err # 仅显示错误及以上级别

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

4.2 日志优先级

1
2
3
4
5
6
7
8
0: emerg     —— 系统不可用
1: alert —— 必须立即处理
2: crit —— 严重错误
3: err —— 错误
4: warning —— 警告
5: notice —— 注意
6: info —— 信息
7: debug —— 调试

4.3 日志管理

1
2
3
4
5
6
7
8
# 查看日志占用磁盘空间
journalctl --disk-usage

# 清理日志,保留最近 2 天
sudo journalctl --vacuum-time=2d

# 限制日志最大大小(在 /etc/systemd/journald.conf 中配置)
# SystemMaxUse=500M

五、Timer —— systemd 的定时任务

systemd Timer 可以替代 cron,提供更精确的控制和更好的日志集成。

5.1 创建 Timer

创建一个执行备份脚本的 Timer:

/etc/systemd/system/backup.service

1
2
3
4
5
6
[Unit]
Description=Daily Backup Script

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

/etc/systemd/system/backup.timer

1
2
3
4
5
6
7
8
9
10
11
[Unit]
Description=Run backup daily at 2:30 AM

[Timer]
OnCalendar=daily
OnCalendar=*-*-* 02:30:00
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target

5.2 Timer 常用指令

1
2
3
4
5
6
7
8
9
# 启用并启动 Timer
sudo systemctl enable backup.timer
sudo systemctl start backup.timer

# 查看所有 Timer
systemctl list-timers --all

# 手动触发一次
sudo systemctl start backup.service

5.3 OnCalendar 时间表达式

1
2
3
4
Mon *-*-* 00:00:00    —— 每周一零点
*-*-* 00,12:00:00 —— 每天零点和中点
*-*-* 00:00/15 —— 每天每 15 分钟(00:00、00:15、00:30…)
*-*-01..07 00:00:00 —— 每月前 7 天零点

六、Target —— 运行级别管理

Target 是 systemd 中的运行级别概念。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看当前默认运行级别
systemctl get-default

# 设置为命令行模式
sudo systemctl set-default multi-user.target

# 设置为图形界面模式
sudo systemctl set-default graphical.target

# 切换到命令行模式(立即生效)
sudo systemctl isolate multi-user.target

# 查看所有 Target
systemctl list-units --type=target --all
Target对应 SysV 级别说明
poweroff.target0关机
rescue.target1单用户维护模式
multi-user.target3多用户命令行模式
graphical.target5图形界面模式
reboot.target6重启

七、实用技巧与排错

7.1 系统启动耗时分析

1
2
3
4
5
6
7
8
# 查看系统启动总耗时
systemd-analyze

# 查看每个服务的启动耗时
systemd-analyze blame

# 可视化依赖链
systemd-analyze critical-chain

7.2 服务排错流程

当服务启动失败时,按以下步骤排查:

1
2
3
4
5
6
7
8
9
10
11
# 1. 查看完整状态
sudo systemctl status myapp -l

# 2. 查看详细日志
sudo journalctl -u myapp -n 50 --no-pager

# 3. 检查配置文件语法
sudo systemd-analyze verify /etc/systemd/system/myapp.service

# 4. 检查依赖服务状态
sudo systemctl list-dependencies myapp

7.3 环境变量传递

1
2
3
4
5
6
7
8
# 方式一:在 Service 文件中使用 Environment 字段
Environment=MY_VAR=value

# 方式二:从文件读取环境变量
EnvironmentFile=/etc/myapp/env.conf

# 方式三:使用 EnvironmentFile 支持多行
EnvironmentFile=-/etc/myapp/env.conf # 前导 - 表示文件不存在时不报错

7.4 设置 ulimit 限制

1
2
3
4
5
[Service]
LimitNOFILE=65536 # 最大文件描述符数
LimitNPROC=4096 # 最大进程数
LimitCORE=infinity # core dump 大小
LimitRSS=infinity # 最大内存

7.5 开机自启失败排查

如果服务设置了 enable 但开机未启动,检查以下方面:

  1. systemctl is-enabled myapp —— 确认启用状态
  2. systemctl list-dependencies myapp —— 检查依赖是否启动成功
  3. 查看 journalctl -b —— 检查启动阶段日志
  4. 检查服务启动类型(Type=oneshot 时默认不会开机启动,需添加 RemainAfterExit=yes

八、常见问题解答

Q: 修改了 .service 文件后需要做什么?
A: 执行 sudo systemctl daemon-reload 重新加载配置。

Q: enable 和 start 有什么区别?
A: enable 设置开机自启(创建软链接),start 立即启动服务。

Q: mask 和 disable 有什么区别?
A: disable 只是移除开机自启,仍可手动启动。mask 将服务文件链接到 /dev/null,彻底阻止启动。

Q: journalctl 日志太大怎么办?
A: 配置 /etc/systemd/journald.conf 中的 SystemMaxUse 限制大小,或使用 journalctl --vacuum-time= 定期清理。


systemd 虽然初看有些复杂,但掌握核心概念后,你会发现它在服务管理、日志监控和定时任务方面远比传统 SysV + cron + syslog 的组合更强大和统一。希望这份指南能帮助你更好地管理 Linux 服务器上的服务。

本文由AI辅助生成,内容仅供参考

  • 标题: Linux systemd 服务管理完全指南
  • 作者: Someone
  • 创建于 : 2026-06-07 00:25:00
  • 更新于 : 2026-06-18 08:39:57
  • 链接: https://demo-blog.qusite.cn/2026-06-07-systemd-guide/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。