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

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

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

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

启动服务:sudo systemctl start

停止服务:sudo systemctl stop

重启系统:sudo systemctl reboot

查看状态:sudo systemctl status

相关推荐
Elastic 中国社区官方博客8 分钟前
14 个 alerts,1 个 incident:使用 Elasticsearch 中的 ES|QL 衡量 alerting rule 噪声
大数据·运维·数据库·elasticsearch·搜索引擎·全文检索
Lsetea8 分钟前
OpenSSL报permitted subtree violation:证书SAN与CA名称约束排查
运维·https·ssl证书·openssl·证书链
ShayneLee811 分钟前
Nginx只开一个端口!能做什么?(一)
运维·nginx
sukalot12 分钟前
Windows 驱动实例分析系列:libwdi 驱动分析 - libwdi 篇(一)
windows
万联WANFLOW19 分钟前
Docker Hub 镜像拉取慢、timeout 的排查方法
运维·docker·云原生·容器·eureka
奇树谦28 分钟前
Windows 下使用 PowerShell 和 CMD 排查端口占用
windows
Julien200431 分钟前
CGroups 资源控制组
linux·运维·服务器·ssh·学习方法
皓月盈江37 分钟前
Linux Debian系统安装Google Chrome谷歌浏览器教程
linux·chrome·debian·谷歌浏览器
Vcaker38 分钟前
Linux学习37-rook-ceph部署
linux·运维·学习
Mortalbreeze41 分钟前
MySQL 基础篇(二):数据库和数据表的基本操作
linux·服务器·数据库·mysql