记录 systemd 服务管理的常用操作与配置方法,涵盖服务创建、日志查看与故障排查。
基础操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# 启动/停止/重启服务
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
# 查看服务状态
sudo systemctl status nginx
# 设置开机自启/禁止自启
sudo systemctl enable nginx
sudo systemctl disable nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
|
创建自定义服务
以一个 Node.js 应用为例,创建 /etc/systemd/system/myapp.service:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
[Unit]
Description=My Node.js Application
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/myapp
ExecStart=/usr/bin/node app.js
Restart=on-failure
RestartSec=5
Environment=NODE_ENV=production
Environment=PORT=3000
[Install]
WantedBy=multi-user.target
|
启用并启动:
1
2
3
|
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
|
日志管理
systemd 统一通过 journalctl 管理日志:
1
2
3
4
5
6
7
8
9
10
11
|
# 查看指定服务最近日志
sudo journalctl -u nginx --no-pager -n 50
# 实时跟踪日志
sudo journalctl -u myapp -f
# 按时间范围查询
sudo journalctl -u myapp --since "2026-11-09 23:00" --until "2026-11-10 01:00"
# 查看本次启动以来的所有日志
sudo journalctl -b
|
常见故障排查
服务启动失败
1
2
3
|
# 查看详细错误
sudo systemctl status myapp
sudo journalctl -u myapp -n 30 --no-pager
|
常见原因:
ExecStart 路径错误或缺少执行权限。
User 指定的用户无权限访问工作目录。
- 环境变量缺失导致应用启动异常。
- 端口被占用。
服务反复重启
检查 Restart 策略与 RestartSec 间隔,查看应用日志确认是否因 OOM 或异常退出。
1
2
|
# 检查是否被 OOM Killer 杀死
dmesg | grep -i oom
|
资源限制
通过 systemd 可以对服务做资源隔离:
1
2
3
4
5
6
7
8
9
10
11
12
|
[Service]
# CPU 限制
CPUQuota=50%
# 内存限制
MemoryMax=512M
# 文件描述符限制
LimitNOFILE=65536
# 进程数限制
TasksMax=100
|
修改后执行 systemctl daemon-reload 并重启服务生效。
小结
systemd 是现代 Linux 的服务管理核心,掌握其配置与日志排查能力是运维基本功。后续会记录 systemd timer 定时任务与 cron 的对比实践。