深色模式
systemd 入门
摘要:现代 Linux 用 systemd 管理开机与服务。本文讲清
systemctl的启停、自启、状态查看,以及写一个简单的服务单元。
一、管理已有服务
bash
systemctl status sshd # 查看状态
sudo systemctl start nginx # 启动
sudo systemctl stop nginx # 停止
sudo systemctl restart nginx # 重启
sudo systemctl reload nginx # 平滑重载配置
sudo systemctl enable nginx # 开机自启
sudo systemctl disable nginx # 取消自启
systemctl is-enabled nginx # 是否自启1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
二、看服务日志
bash
journalctl -u nginx # 该服务的全部日志
journalctl -u nginx -f # 实时跟踪
journalctl -u nginx --since "10 min ago"1
2
3
2
3
三、写一个简单的服务单元
/etc/systemd/system/myapp.service:
ini
[Unit]
Description=My App
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/myapp/app.py
Restart=on-failure
User=ops
[Install]
WantedBy=multi-user.target1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
bash
sudo systemctl daemon-reload # 改了单元文件必须重载
sudo systemctl enable --now myapp1
2
2
Restart 策略
Restart=on-failure 会在进程异常退出时自动拉起,但频繁崩溃会反复重启——要结合日志排查根因,别指望靠重启掩盖问题。
验证
- [ ] 能 start/stop/enable 一个服务
- [ ]
journalctl -u能看到服务日志 - [ ] 自写单元
enable --now后开机自启生效
常见坑
- 改了 unit 不 reload:必须
daemon-reload否则不生效。 - ExecStart 路径错:用绝对路径,脚本自身也要可执行。
- 依赖顺序:
After=写错会导致启动过早失败。