主题
08 · systemd 服务与开机自启
目标:读懂 unit,会用
systemctl启停与看日志,并写一个最小服务。
官方:systemd 文档
1. 环境前提
- Ubuntu 云机(systemd 为默认 init)
- WSL:需已启用 systemd 才有完整体验;否则本篇以云机为准
2. 为什么用 systemd
| 裸跑 | systemd |
|---|---|
| SSH 断了进程可能没了 | 与会话解耦 |
| 崩溃了要人盯 | 可 Restart= |
| 开机要手动启 | enable 开机自启 |
| 日志散落 | 统一 journalctl -u |
前端熟悉的 PM2 / nohup:在服务器上优先学 systemd(发行版标准做法)。
3. systemctl 日常
以 Nginx 为例(04 已装):
bash
sudo systemctl status nginx
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # 支持的话:热加载配置
sudo systemctl enable nginx # 开机自启
sudo systemctl disable nginx1
2
3
4
5
6
7
2
3
4
5
6
7
日志:
bash
sudo journalctl -u nginx -n 50 --no-pager
sudo journalctl -u nginx -f1
2
2
列服务:
bash
systemctl list-units --type=service --state=running1
4. unit 文件长什么样
系统单元常在:
| 路径 | 用途 |
|---|---|
/lib/systemd/system/ 或 /usr/lib/systemd/system/ | 包自带 |
/etc/systemd/system/ | 你自定义,优先放这 |
最小示例:跑一个循环脚本(练手;第 10 篇换成真正的 Node/Go)。
bash
mkdir -p ~/lab/mini-svc
cat > ~/lab/mini-svc/tick.sh <<'EOF'
#!/usr/bin/env bash
while true; do
echo "tick $(date -Is)" >> /tmp/mini-tick.log
sleep 30
done
EOF
chmod 755 ~/lab/mini-svc/tick.sh1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
写 unit(把 YOUR_USER 换成 whoami):
bash
sudo tee /etc/systemd/system/mini-tick.service > /dev/null <<EOF
[Unit]
Description=Mini tick lab service
After=network.target
[Service]
Type=simple
User=YOUR_USER
ExecStart=/home/YOUR_USER/lab/mini-svc/tick.sh
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
加载并启动:
bash
sudo systemctl daemon-reload
sudo systemctl start mini-tick
sudo systemctl status mini-tick
tail -f /tmp/mini-tick.log1
2
3
4
2
3
4
开机自启:
bash
sudo systemctl enable mini-tick1
停用并删除(练完清理):
bash
sudo systemctl disable --now mini-tick
sudo rm /etc/systemd/system/mini-tick.service
sudo systemctl daemon-reload1
2
3
2
3
5. 读 status 时看什么
text
Active: active (running) ...
Main PID: ...
journal 里的报错行1
2
3
2
3
常见失败:ExecStart 路径错、没有执行位、User= 无权写日志路径、依赖的端口被占。
6. 云机 vs WSL
| 云 Ubuntu | WSL2 | |
|---|---|---|
| systemd | 默认有 | 较新版本可开;旧环境可能没有 |
enable 开机 | 虚拟机/云主机重启后生效 | 依赖 WSL 启动方式 |
7. 动手清单
- [ ]
systemctl status nginx读懂 Active 行 - [ ] 写出并启动
mini-tick.service - [ ]
journalctl -u mini-tick -n 20能看到记录(若脚本只写文件,status 仍应为 running) - [ ]
enable后(可选)重启云机验证仍在跑 - [ ] 练完按上文清理 unit(或留到 10 再删)
8. 常见翻车
| 翻车 | 处理 |
|---|---|
| 改了 unit 不生效 | daemon-reload 后再 restart |
status 显示 activating (auto-restart) | Exec 一启动就崩;看 journal,修命令 |
| 用 root 跑业务 | 改为 User= 普通用户;文件权限给够 |
路径写了 ~ | unit 里 不要用 ~,写绝对路径 |
9. 官方入口
- systemd.service
- systemctl
man systemctl、man systemd.service
下一篇:Nginx 静态站与反向代理 —— 把本机端口转到 80。
OS 深读:23 · 信号、中断与进程如何结束(对照 systemctl stop)。
