服务管理
概述
服务(也称为守护进程)是在后台运行的程序,提供各种系统功能。现代 Linux 系统使用 systemd 作为初始化系统和服务管理器。
systemd 简介
systemd 是大多数现代 Linux 发行版的初始化系统,负责:
- 引导系统
- 管理服务
- 管理挂载点
- 管理设备
- 管理日志
核心概念
| 概念 | 说明 |
|---|---|
| Unit | systemd 管理的基本单位 |
| Service | 服务单元,运行守护进程 |
| Target | 目标单元,组合多个单元 |
| Socket | 套接字单元,管理套接字 |
| Timer | 定时器单元,计划任务 |
Unit 文件位置
| 路径 | 说明 |
|---|---|
/lib/systemd/system/ | 系统单元文件 |
/etc/systemd/system/ | 管理员自定义单元 |
/run/systemd/system/ | 运行时单元 |
~/.config/systemd/user/ | 用户单元 |
systemctl 命令
管理服务
bash
# 启动服务
$ sudo systemctl start nginx
# 停止服务
$ sudo systemctl stop nginx
# 重启服务
$ sudo systemctl restart nginx
# 重新加载配置(不中断服务)
$ sudo systemctl reload nginx
# 重新加载或重启
$ sudo systemctl reload-or-restart nginx
# 查看服务状态
$ systemctl status nginx
● nginx.service - A high performance web server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2025-01-09 10:00:00 CST; 2h ago
Process: 1234 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
Main PID: 1235 (nginx)
Tasks: 3 (limit: 4915)
Memory: 10.0M
CGroup: /system.slice/nginx.service
├─1235 nginx: master process /usr/sbin/nginx
└─1236 nginx: worker process
# 检查服务是否活动
$ systemctl is-active nginx
active
# 检查服务是否失败
$ systemctl is-failed nginx
active开机自启
bash
# 启用开机自启
$ sudo systemctl enable nginx
# 禁用开机自启
$ sudo systemctl disable nginx
# 启用并立即启动
$ sudo systemctl enable --now nginx
# 禁用并立即停止
$ sudo systemctl disable --now nginx
# 检查是否启用
$ systemctl is-enabled nginx
enabled
# 屏蔽服务(完全禁止启动)
$ sudo systemctl mask nginx
# 取消屏蔽
$ sudo systemctl unmask nginx列出服务
bash
# 列出所有服务
$ systemctl list-units --type=service
# 列出运行中的服务
$ systemctl list-units --type=service --state=running
# 列出已安装的服务
$ systemctl list-unit-files --type=service
# 列出失败的服务
$ systemctl list-units --failed
# 列出所有单元
$ systemctl list-units
# 列出依赖
$ systemctl list-dependencies nginx系统状态
bash
# 查看系统状态
$ systemctl status
# 重新加载 systemd 配置
$ sudo systemctl daemon-reload
# 查看默认目标
$ systemctl get-default
graphical.target
# 设置默认目标
$ sudo systemctl set-default multi-user.target # 多用户(无图形)
$ sudo systemctl set-default graphical.target # 图形界面
# 切换运行级别
$ sudo systemctl isolate multi-user.target
$ sudo systemctl isolate graphical.target电源管理
bash
# 关机
$ sudo systemctl poweroff
# 重启
$ sudo systemctl reboot
# 挂起
$ sudo systemctl suspend
# 休眠
$ sudo systemctl hibernate
# 混合休眠
$ sudo systemctl hybrid-sleep编写 Service 单元文件
基本结构
ini
[Unit]
Description=My Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/myapp
Restart=always
[Install]
WantedBy=multi-user.target[Unit] 部分
ini
[Unit]
Description=Service description
Documentation=https://example.com/docs
After=network.target mysql.service
Requires=mysql.service
Wants=redis.service
Conflicts=other.service| 选项 | 说明 |
|---|---|
| Description | 服务描述 |
| Documentation | 文档链接 |
| After | 在指定单元后启动 |
| Before | 在指定单元前启动 |
| Requires | 依赖的单元(失败则停止) |
| Wants | 依赖的单元(失败不影响) |
| Conflicts | 冲突的单元 |
[Service] 部分
ini
[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www
ExecStart=/usr/bin/myapp --config /etc/myapp.conf
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
Restart=on-failure
RestartSec=5
Environment=NODE_ENV=production
EnvironmentFile=/etc/myapp/env| 选项 | 说明 |
|---|---|
| Type | 服务类型 |
| User/Group | 运行用户/组 |
| WorkingDirectory | 工作目录 |
| ExecStart | 启动命令 |
| ExecStop | 停止命令 |
| ExecReload | 重载命令 |
| Restart | 重启策略 |
| RestartSec | 重启间隔 |
| Environment | 环境变量 |
| EnvironmentFile | 环境变量文件 |
Type 类型
| 类型 | 说明 |
|---|---|
| simple | 默认,主进程即服务进程 |
| forking | 服务 fork 后父进程退出 |
| oneshot | 一次性任务 |
| notify | 服务就绪后发送通知 |
| idle | 等待其他任务完成 |
Restart 策略
| 策略 | 说明 |
|---|---|
| no | 不重启 |
| always | 总是重启 |
| on-success | 成功退出时重启 |
| on-failure | 失败时重启 |
| on-abnormal | 异常退出时重启 |
| on-abort | 收到信号时重启 |
[Install] 部分
ini
[Install]
WantedBy=multi-user.target
Alias=myservice.service| 选项 | 说明 |
|---|---|
| WantedBy | 被哪个目标依赖 |
| RequiredBy | 被哪个目标强依赖 |
| Alias | 别名 |
示例:Node.js 应用
ini
# /etc/systemd/system/myapp.service
[Unit]
Description=My Node.js Application
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myapp
Environment=NODE_ENV=production
Environment=PORT=3000
[Install]
WantedBy=multi-user.target示例:Python 应用
ini
# /etc/systemd/system/flask-app.service
[Unit]
Description=Flask Application
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/flask-app
Environment="PATH=/var/www/flask-app/venv/bin"
ExecStart=/var/www/flask-app/venv/bin/gunicorn --workers 3 --bind unix:flask-app.sock -m 007 app:app
Restart=always
[Install]
WantedBy=multi-user.target创建和启用服务
bash
# 1. 创建服务文件
$ sudo vim /etc/systemd/system/myapp.service
# 2. 重新加载 systemd
$ sudo systemctl daemon-reload
# 3. 启动服务
$ sudo systemctl start myapp
# 4. 检查状态
$ systemctl status myapp
# 5. 启用开机自启
$ sudo systemctl enable myapp查看日志
journalctl
bash
# 查看所有日志
$ journalctl
# 查看指定服务的日志
$ journalctl -u nginx
# 实时追踪日志
$ journalctl -u nginx -f
# 查看今天的日志
$ journalctl --since today
# 查看最近 1 小时
$ journalctl --since "1 hour ago"
# 查看指定时间范围
$ journalctl --since "2025-01-09 10:00:00" --until "2025-01-09 12:00:00"
# 查看最后 100 行
$ journalctl -n 100
# 查看内核日志
$ journalctl -k
# 查看启动日志
$ journalctl -b
$ journalctl -b -1 # 上次启动
# 按优先级过滤
$ journalctl -p err # 错误及以上
# 输出为 JSON
$ journalctl -u nginx -o json-pretty
# 查看磁盘使用
$ journalctl --disk-usage
# 清理旧日志
$ sudo journalctl --vacuum-time=7d # 保留 7 天
$ sudo journalctl --vacuum-size=500M # 保留 500MB定时任务:Timer
Timer 单元文件
ini
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily Backup Timer
[Timer]
OnCalendar=daily
OnCalendar=*-*-* 03:00:00
Persistent=true
Unit=backup.service
[Install]
WantedBy=timers.targetini
# /etc/systemd/system/backup.service
[Unit]
Description=Backup Service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.shTimer 时间格式
bash
# 固定间隔
OnBootSec=5min # 启动后 5 分钟
OnUnitActiveSec=1h # 上次运行后 1 小时
# 日历时间
OnCalendar=hourly # 每小时
OnCalendar=daily # 每天
OnCalendar=weekly # 每周
OnCalendar=monthly # 每月
OnCalendar=*-*-* 03:00:00 # 每天凌晨 3 点
OnCalendar=Mon *-*-* 09:00:00 # 每周一早 9 点管理 Timer
bash
# 列出所有 timer
$ systemctl list-timers
# 启动 timer
$ sudo systemctl start backup.timer
# 启用开机自启
$ sudo systemctl enable backup.timer
# 查看 timer 状态
$ systemctl status backup.timer传统 init 系统
service 命令
bash
# 启动服务
$ sudo service nginx start
# 停止服务
$ sudo service nginx stop
# 重启服务
$ sudo service nginx restart
# 查看状态
$ sudo service nginx status
# 列出所有服务
$ service --status-allupdate-rc.d(Debian 系)
bash
# 启用开机自启
$ sudo update-rc.d nginx defaults
# 禁用开机自启
$ sudo update-rc.d nginx disable小结
本章介绍了 Linux 服务管理:
- systemctl 命令:启动、停止、重启、启用服务
- 编写服务文件:Unit、Service、Install 部分
- 日志管理:journalctl
- 定时任务:Timer 单元
systemd 是现代 Linux 系统的核心,掌握它是系统管理的必备技能。
上一章:软件包管理
下一章:网络基础