原标题:systemd和service
systemd 是 Linux 的初始化系统(Init System)和服务管理器。
它主要负责:
- 开机启动整个系统(PID 1)
- 启动各种服务(SSH、Nginx、Docker……)
- 管理服务生命周期
- 管理日志
- 管理定时任务
- 管理挂载
- 管理用户登录
- 管理网络(部分发行版)
Linux Kernel
│
▼
systemd (PID 1)
│
├───────────────┐
│ │
sshd nginx
docker mysql
cron...
systemd 的思想就是:把所有东西都抽象成 Unit(单元)
| 类型 | 作用 |
|---|---|
| service | 服务 |
| socket | Socket 激活 |
| target | 一组 Unit |
| mount | 挂载 |
| automount | 自动挂载 |
| timer | 定时器 |
| path | 文件变化触发 |
| device | 设备 |
| swap | Swap |
| slice | 资源分组 |
| scope | 外部进程 |
systemd 是现在主流 Linux 发行版(包括 Debian、Ubuntu)的初始化系统和服务管理器,取代了传统的 SysV init。
什么是 Service
Service 就是一个后台服务。
例如:
nginx.service
docker.service
sshd.service
mysql.service
查看:
systemctl list-units--type=service
查看所有(包括未运行):
systemctl list-unit-files
systemctl命令
systemctl 是管理 systemd 的命令。
比如:
启动
sudo systemctlstart nginx
停止
sudo systemctlstop nginx
重启
sudo systemctlrestart nginx
查看状态
systemctl status nginx
重新加载配置
sudo systemctl reload nginx
常用命令
服务管理:
systemctl start/stop/restart nginx
systemctl enable/disable nginx # 开机自启
systemctl status nginx
systemctl daemon-reload # 修改 unit 文件后重载配置
日志查看(journald):
journalctl -u nginx.service # 查看某服务日志
journalctl -f # 实时跟踪
journalctl --since "1 hour ago"
journalctl -p err # 按优先级过滤
系统状态:
systemctl list-units --type=service
systemctl list-unit-files
systemd-analyze blame # 查看启动耗时
systemd-analyze critical-chain # 启动关键路径
注意:
- 修改 unit 文件后忘记
daemon-reload,改动不会生效 Restart=on-failure配置不当可能导致故障服务无限重启,占用资源- journald 日志默认可能无限增长,占满磁盘(可用
SystemMaxUse=限制) - 直接编辑
/lib/systemd/system/下的文件在包更新时会被覆盖,应在/etc/systemd/system/下创建或用systemctl edit生成 override
如果这篇文章对你有帮助,点个赞吧。


