systemd 是 Linux 操作系统的中央化系统和服务管理器,也是大多数现代 Linux 发行版的默认初始化(init)系统。Linux 启动时,它负责按照配置启动服务、安排依赖顺序,并根据配置处理进程退出和重启。自 2010 年发布以来,它已被 Ubuntu、CentOS、Debian 等主流发行版默认采用,取代了传统的 SysV init 系统。
传统 init 系统采用串行方式启动服务,脚本复杂且启动缓慢。systemd 通过并行启动、依赖分析和统一管理,彻底改变了 Linux 系统的启动与管理方式。
核心作用-
- 作为 1 号进程(PID 1):它是内核在系统引导时启动的第一个用户空间进程,负责初始化系统并一直运行到关机。
- 并行启动服务:它能分析各个系统服务(如网络、磁盘挂载)之间的依赖关系,在开机时同时启动多个服务,大幅缩短开机时间。
- 管理系统服务:它统一管理后台守护进程(Daemon),并在服务意外崩溃时自动重新启动它们。
核心概念:
Unit(单元)systemctl 是管理 systemd 的主要工具,统一格式为 systemctl <动作> <服务名>:
服务管理:
- 启动服务:
sudo systemctl start nginx - 停止服务:
sudo systemctl stop nginx - 重启服务:
sudo systemctl restart nginx - 查看状态:
sudo systemctl status nginx
开机自启:
- 设置开机自启:
sudo systemctl enable nginx - 取消开机自启:
sudo systemctl disable nginx - 查看所有自启项:
systemctl list-unit-files
系统控制:
- 重启系统:
sudo systemctl reboot - 关机:
sudo systemctl poweroff
实战案例:部署一个自定义服务
下面通过一个完整示例,演示如何用 systemd 管理一个自定义 Python 脚本。
1. 创建脚本文件 /opt/myapp.py:
python
#!/usr/bin/env python3
import time
while True:
print("MyApp is running...")
time.sleep(5)
2. 创建 Unit 文件 /etc/systemd/system/myapp.service:
ini
[Unit]
Description=My Custom Python App
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/myapp.py
Restart=always
User=nobody
[Install]
WantedBy=multi-user.target
3. 重新加载配置并启动服务:
bash
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl status myapp
4. 设置开机自启:
bash
sudo systemctl enable myapp
总结
systemd 作为现代 Linux 系统的核心组件,通过并行启动、Unit 抽象和统一管理,大幅提升了系统启动速度和管理效率。掌握 systemctl 命令和 Unit 配置,是每个 Linux 运维人员的基本功。
如需深入学习,可查阅 man systemd 和 man systemctl 获取完整文档。*:对一组 Unit 进行分组,用于实现启动级别
.mount:管理文件系统挂载点
Unit 文件通常存放在 /etc/systemd/system/ 目录下,通过 systemctl 命令进行管理。
常用命令systemctl 是管理 systemd 的主要工具:
启动服务:sudo systemctl start
停止服务:sudo systemctl stop
重启系统:sudo systemctl reboot
查看状态:sudo systemctl status