服务安装检测和开机重启
什么是 systemd
systemd 是 Linux 系统里的一个 系统管理器和服务管理工具。
简单理解:
👉 它负责启动、停止和管理系统里的各种服务。
例如:
- Web 服务器(nginx)
- 数据库(mysql)
- Docker
这些程序如果作为 后台服务运行,通常都是由 systemd 管理。
systemd 可以做什么
1️⃣ 启动服务
1 | systemctl start nginx |
2️⃣ 停止服务
1 | systemctl stop nginx |
3️⃣ 重启服务
1 | systemctl restart nginx |
4️⃣ 查看状态
1 | systemctl status nginx |
什么是 service 文件
比如安装cliproxyapi,之后找到~/cliproxyapi目录下的cliproxy.service文件。
1 | cliproxyapi.service |
这是 systemd 的服务配置文件。
一般放在:
1 | /etc/systemd/system/ |
里面会定义:
- 程序在哪里
- 如何启动
- 是否开机启动
- 用哪个用户运行
例如:
1 | [Unit] |
为什么部署程序要用 systemd
好处很多:
✅ 开机自动启动
✅ 程序崩了自动重启
✅ 统一管理日志
✅ 后台运行
✅ 方便运维
将服务安装到systemd
1 | cd ~/cliproxyapi |
检查它是否被systemd识别:
1 | systemctl status cliproxyapi.service --no-pager |
设置服务自动重启
启动+开机自启
1 | sudo systemctl enable --now cliproxyapi.service |
看日志:
1 | sudo journalctl -u cliproxyapi.service -e --no-pager |
查看服务
1️⃣ 查看当前正在运行的服务
1 | systemctl list-units --type=service |
只显示 正在运行的 service。
2️⃣ 查看所有服务(包含未运行)
1 | systemctl list-unit-files --type=service |
会看到类似:
1 | nginx.service enabled |
状态说明:
- enabled → 开机启动
- disabled → 不开机启动
- static → 依赖服务
3️⃣ 查看所有正在运行的服务(最常用)
1 | systemctl --type=service --state=running |
4️⃣ 搜索某个服务
比如查你的 cliproxyapi
1 | systemctl list-unit-files | grep cliproxyapi |
或
1 | systemctl list-units | grep cliproxyapi |
5️⃣ 查看某个服务详细状态
1 | systemctl status cliproxyapi |
6️⃣ 查看系统所有 unit(包括 socket、timer 等)
1 | systemctl list-units |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 ahao430 的博客!
评论