systemd 是什么?

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 systemdman systemctl 获取完整文档。*:对一组 Unit 进行分组,用于实现启动级别

  • .mount:管理文件系统挂载点

Unit 文件通常存放在 /etc/systemd/system/ 目录下,通过 systemctl 命令进行管理。

常用命令systemctl 是管理 systemd 的主要工具:

启动服务:sudo systemctl start

停止服务:sudo systemctl stop

重启系统:sudo systemctl reboot

查看状态:sudo systemctl status

相关推荐
暖核1 小时前
华为云运维三件套实战:云审计 + 云监控 + 云日志完整操作指南
linux·运维·华为云
hhb_6181 小时前
智能任务自动化协同AI工作流技术文档
运维·人工智能·自动化
小溪学编程1 小时前
Java ListIterator 接口详解:双向遍历与列表修改的利器
java·开发语言·windows
AI+程序员在路上1 小时前
Rv1126b与手机(SPP蓝牙串口APP)蓝牙通信流程
linux·c语言·智能手机
虚无的纽扣1 小时前
【Linux】进程第二课:进程优先级和环境变量
linux·运维·服务器
maosheng11462 小时前
【无标题】linux中企业容易考的的小知识点1(rhcsa)
linux·运维·服务器
牢姐与蒯2 小时前
Linux进程(九).自定义shell——深度理解命令行和shell
linux·运维·服务器
snow@li2 小时前
服务器运维:mysql 安装笔记
运维·服务器·mysql
天道jimmy2 小时前
VulnHub 系列:View2aKill,1
linux·运维·服务器