Linux Systemd服务管理从入门到实战(自定义服务+全套命令)

Linux Systemd服务管理从入门到实战(自定义服务+全套命令)

在 Linux 运维工作中,服务管理是重中之重。开机自启、服务启停、配置重载、守护进程托管、异常重启,全部依赖 Systemd 机制。

CentOS 7 / Ubuntu 16.04+ 全部默认采用 Systemd 管理系统与服务,彻底替代传统 init 机制。本文从零讲解 Systemd 原理、Unit 单元、全套 systemctl 命令、配置文件详解,最后带大家手写开发一个自定义守护服务,适合实训、面试、工作落地!

一、Systemd 是什么?核心优势

1.1 Windows 与 Linux 自启对比

Windows 开机自动启动程序、后台服务,可通过命令:services.msc 图形化管理。

Linux(CentOS7+)使用 Systemd统一管理所有系统服务、开机流程、守护进程。

1.2 Systemd 核心特点

  • 并行启动:无依赖的服务全部并行启动,大幅加快开机速度

  • 按需启动:很多服务仅做标记,不真正占用资源,被访问时才真正启动

  • 统一管理:进程、服务、挂载、定时、设备全部抽象为 Unit 管理

  • 自动重启:支持服务崩溃自动重启,保障业务常驻

Systemd 的设计目标:为系统启动、服务生命周期、资源管控提供一套完整解决方案

1.3 系统两大顶级进程(PID 1 / PID 2)

  • 内核空间:kthreadd,PID=2:负责内核层所有后台线程

  • 用户空间:systemd,PID=1:所有用户进程的父进程,接管系统所有服务与进程管理

二、服务与守护进程(Daemon)通俗理解

2.1 核心概念区分

  • 服务:业务层面的名称,对外提供能力(Web服务、数据库服务、培训服务)

  • 守护进程:后台常驻程序,真正干活的进程,静默运行、对外响应请求

2.2 经典类比

互联网业务

  • 服务:Web 网站服务

  • 守护进程:httpd / nginx

2.3 实操:httpd 服务与守护进程对应关系

# 安装httpd服务
[root@centos7 ~ 18:33:14]# yum -y install httpd

# 启动服务
[root@centos7 ~ 18:58:09]# systemctl start httpd

# 查看服务守护进程树
[root@centos7 ~ 18:58:56]# ps -C httpd f
   PID TTY      STAT   TIME COMMAND
  4887 ?        Ss     0:00 /usr/sbin/httpd -DFOREGROUND
  4893 ?        S      0:00  \_ /usr/sbin/httpd -DFOREGROUND
  4894 ?        S      0:00  \_ /usr/sbin/httpd -DFOREGROUND
  4895 ?        S      0:00  \_ /usr/sbin/httpd -DFOREGROUND
  4896 ?        S      0:00  \_ /usr/sbin/httpd -DFOREGROUND
  4897 ?        S      0:00  \_ /usr/sbin/httpd -DFOREGROUND

可见:httpd 服务由主进程+多个子守护进程共同提供服务

三、Systemd 架构

  • 核心守护进程systemd(PID=1),后台常驻,全权管理系统资源
  • 用户操作工具systemctl,运维唯一交互命令,实现所有服务管理操作

在这里插入图片描述

四、Systemd 十大 Unit 单元类型

Systemd 将系统所有可管理资源抽象为 Unit 单元,不同后缀对应不同功能。

单元类型后缀作用说明
Service.service系统服务管理(最常用)
Socket.socket进程间通信套接字
Target.target运行级别、服务组管理
Timer.timer定时任务(替代crontab)
Device.device内核硬件设备管理
Mount.mount文件系统挂载管理
Swap.swap交换分区管理
Automount.automount自动挂载
Path.path监控文件变化触发服务
Slice.slice系统资源限制与分组

五、Unit 查看命令大全

5.1 查看各类单元列表

# 查看已加载所有unit
[fangbing@centos7 ~ 19:02:54]$ systemctl list-units
UNIT                                                        LOAD   ACTIVE SUB       DESCRIPTION
proc-sys-fs-binfmt_misc.automount                           loaded active waiting   Arbitrary Executable File Formats File System Automount Poi
sys-devices-pci0000:00-0000:00:07.1-ata2-host2-target2:0:0-2:0:0:0-block-sr0.device loaded active plugged   VMware_Virtual_IDE_CDROM_Drive Cent
sys-devices-pci0000:00-0000:00:10.0-host0-target0:0:0-0:0:0:0-block-sda-sda1.device loaded active plugged   VMware_Virtual_S 1
sys-devices-pci0000:00-0000:00:10.0-host0-target0:0:0-0:0:0:0-block-sda-sda2.device loaded active plugged   VMware_Virtual_S 2
sys-devices-pci0000:00-0000:00:10.0-host0-target0:0:0-0:0:0:0-block-sda.device loaded active plugged   VMware_Virtual_S

# 只查看定时器单元(-t:指定类型)
[fangbing@centos7 ~ 19:04:26]$ systemctl list-units -t timer 
UNIT                         LOAD   ACTIVE SUB     DESCRIPTION
systemd-tmpfiles-clean.timer loaded active waiting Daily Cleanup of Temporary Directories
unbound-anchor.timer         loaded active waiting daily update of the root trust anchor for DNSSEC

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

2 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

# 查看所有服务(含开启/关闭)
[fangbing@centos7 ~ 19:04:57]$ systemctl list-units --type service --all
 UNIT                                                  LOAD      ACTIVE   SUB     DESCRIPTION
  abrt-ccpp.service                                     loaded    active   exited  Install ABRT coredump hook
  abrt-oops.service                                     loaded    active   running ABRT kernel log watcher
  abrt-vmcore.service                                   loaded    inactive dead    Harvest vmcores for ABRT
  abrt-xorg.service                                     loaded    active   running ABRT Xorg log watcher
  abrtd.service                                         loaded    active   running ABRT Automated Bug Reporting Tool
  accounts-daemon.service                               loaded    active   running Accounts Service
  apparmor.service                                      not-found inactive dead    apparmor.service

# 查看系统所有单元配置文件
[fangbing@centos7 ~ 19:07:08]$ systemctl list-unit-files 
UNIT FILE                                     STATE   
proc-sys-fs-binfmt_misc.automount             static  
dev-hugepages.mount                           static  
dev-mqueue.mount                              static  
proc-fs-nfsd.mount                            static  
proc-sys-fs-binfmt_misc.mount                 static  
run-vmblock\x2dfuse.mount                     disabled

# 查看启动失败的服务,当前没有失败单元服务
[fangbing@centos7 ~ 19:10:09]$ systemctl --failed --type service 
0 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

# 查看单个服务详细信息
[fangbing@centos7 ~ 19:11:05]$ systemctl status sshd.service 
● sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
   Active: active (running) since 三 2026-07-22 16:59:17 CST; 2h 14min ago
     Docs: man:sshd(8)
           man:sshd_config(5)
 Main PID: 1219 (sshd)
    Tasks: 1
   CGroup: /system.slice/sshd.service
           └─1219 /usr/sbin/sshd -D

722 16:59:17 centos7.fangbing.cloud systemd[1]: Starting OpenSSH server daemon...
722 16:59:17 centos7.fangbing.cloud sshd[1219]: Server listening on 0.0.0.0 port 22.
722 16:59:17 centos7.fangbing.cloud sshd[1219]: Server listening on :: port 22.
722 16:59:17 centos7.fangbing.cloud systemd[1]: Started OpenSSH server daemon.
722 16:59:38 centos7.fangbing.cloud sshd[1898]: Accepted password for fangbing from 10.1.8.1 port 50556 ssh2
722 18:12:09 centos7.fangbing.cloud sshd[3646]: Accepted password for root from 10.1.8.1 port 59563 ssh2
722 18:16:08 centos7.fangbing.cloud sshd[3791]: Accepted password for root from 10.1.8.1 port 59695 ssh2

5.2 字段含义说明

  • UNIT:单元名称

  • LOAD:配置文件是否成功加载解析

  • ACTIVE:高级别运行状态

  • SUB:详细子状态

  • DESCRIPTION:服务描述

5.3 服务状态关键字释义

  • loaded:配置已加载

  • active(running):正在运行

  • active(exited):一次性任务执行完毕

  • active(waiting):运行中、等待事件触发

  • inactive:已停止

  • enabled:开机自启开启

  • disabled:开机自启关闭

  • static:不可手动启动,依赖别的服务触发

六、systemctl 服务控制核心命令(生产常用)

命令功能说明
systemctl status 服务名查看服务状态、日志、PID
systemctl start 服务名启动服务
systemctl stop 服务名停止服务
systemctl restart 服务名重启服务(stop+start)
systemctl reload 服务名重载配置,不重启主进程
systemctl enable 服务名设置开机自启
systemctl disable 服务名关闭开机自启
systemctl mask 服务名彻底禁用服务,无法启动
systemctl unmask 服务名解除禁用
systemctl is-enabled 服务名查看是否开机自启

6.1 实操演示:sshd 服务启停、自启管理

# 停止服务
[root@centos7 ~ 18:59:09]# systemctl stop sshd.service 
[root@centos7 ~ 19:15:54]# systemctl is-active sshd
inactive

# 启动服务
[root@centos7 ~ 19:16:11]# systemctl start sshd
[root@centos7 ~ 19:16:43]# systemctl is-active sshd
active

# 重启服务(相当于stop再start)
[root@centos7 ~ 19:16:54]# systemctl restart sshd

# 重载配置(修改sshd_config后使用,重新加载服务,服务对应的主进程不会重启,只会重新加载一次配置文件)
[root@centos7 ~ 19:17:32]# systemctl reload sshd

# 关闭开机自启
[root@centos7 ~ 19:18:21]# systemctl disable sshd
Removed symlink /etc/systemd/system/multi-user.target.wants/sshd.service.
[root@centos7 ~ 19:20:01]# systemctl is-enabled sshd
disabled

# 开启开机自启
[root@centos7 ~ 19:20:22]# systemctl enable sshd 
Created symlink from /etc/systemd/system/multi-user.target.wants/sshd.service to /usr/lib/systemd/system/sshd.service.
[root@centos7 ~ 19:21:11]# systemctl is-enabled sshd
enabled

# 彻底禁用服务(锁死)
[root@centos7 ~ 19:21:25]# systemctl mask sshd
Created symlink from /etc/systemd/system/sshd.service to /dev/null.

# 重启验证,无法远程连接,且无法statr,原因是服务被禁用后,将无法start,因为服务的配置文件指向/dev/null
[root@centos7 ~ 19:22:01]# reboot

[root@centos7 ~ 19:24:28]# systemctl status sshd
● sshd.service
   Loaded: masked (/dev/null; bad)
   Active: inactive (dead)

722 19:23:05 centos7.fangbing.cloud systemd[1]: Cannot add dependency job...
Warning: sshd.service changed on disk. Run 'systemctl daemon-reload' to reload units.
Hint: Some lines were ellipsized, use -l to show in full.

# 解锁服务,可以开启服务
[root@centos7 ~ 19:24:43]# systemctl unmask sshd
[root@centos7 ~ 19:26:17]# systemctl start sshd
[root@centos7 ~ 19:27:30]# systemctl status sshd
● sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
   Active: active (running) since 三 2026-07-22 19:27:30 CST; 3s ago
     Docs: man:sshd(8)
           man:sshd_config(5)
 Main PID: 2790 (sshd)
    Tasks: 1
   CGroup: /system.slice/sshd.service
           └─2790 /usr/sbin/sshd -D

722 19:27:30 centos7.fangbing.cloud systemd[1]: Starting OpenSSH server d...
722 19:27:30 centos7.fangbing.cloud sshd[2790]: Server listening on 0.0.0...
722 19:27:30 centos7.fangbing.cloud sshd[2790]: Server listening on :: po...
722 19:27:30 centos7.fangbing.cloud systemd[1]: Started OpenSSH server da...
Hint: Some lines were ellipsized, use -l to show in full.

七、Systemd 配置文件路径与详解

7.1 配置文件优先级

  1. /etc/systemd/system/ 自定义配置,优先级最高

  2. /usr/lib/systemd/system/ 系统默认、软件自带配置

7.2 标准 service 文件三大模块详解(以 sshd 为例)

[Unit] 区域:服务描述与依赖
  • Description:服务功能描述

  • Documentation:帮助文档路径

  • After:依赖服务,指定在哪些服务启动完毕再启动当前服务

  • Wants:弱依赖,依赖服务失败不影响当前服务启动

[Service] 区域:服务运行参数
  • Type=notify:服务启动后主动通知 systemd 就绪

  • EnvironmentFile:加载环境变量配置文件

  • ExecStart:服务启动命令

  • ExecReload:重载配置命令

  • KillMode:进程杀死模式

  • Restart=on-failure:异常退出自动重启

  • RestartSec:重启等待间隔时间

[Install] 区域:开机自启配置
  • WantedBy=multi-user.target:多用户模式下开机启动

八、企业级实战:自定义开发 study 守护服务

需求:开发一个自定义 Linux 守护服务,后台永久运行,每5秒写入一条日志,模拟业务常驻进程。

8.1 编写业务脚本

[root@centos7 ~ 19:27:44]# vim /usr/local/bin/study

脚本内容:

#!/bin/bash
# 第一行内容是脚本的 "解释器声明"(shebang),指定该脚本使用 /bin/bash 作为解释器执行。系统会根据这一行找到对应的 shell 程序来解析后续命令。

# 启动一个无限循环:while 是循环关键字,true 是一个永远为真的条件,因此这个循环会一直执行下去,直到被外部终止(如 Ctrl+C)。
while true

# 循环体的开始标记,do 和后面的 done 之间的内容是循环中重复执行的命令。
do

  # 执行 date 命令(获取当前系统时间),并通过 $(...) 捕获其输出,将结果赋值给变量 DATE。
  DATE=$(date)

  # echo 命令输出字符串,其中 $DATE 会被替换为变量的值
  # >> 是追加重定向符号,将输出内容追加到 /var/log/study.log 文件中
  # 最终输出内容类似 Fri Oct 31 10:00:00 CST 2025: I'M studying [ Linux ]。
  echo "$DATE: I'M studying [ Linux ]" >> /var/log/study.log

  # 让脚本暂停执行 5 秒(sleep 命令用于延迟,单位默认为秒),避免循环执行过快。
  sleep 5

# 循环体的结束标记,与前面的 while 和 do 配合,标志着一次循环的结束。
done

8.2 赋予执行权限

[root@centos7 ~ 19:30:57]# chmod +x /usr/local/bin/study 

8.3 新建 systemd 服务配置文件

[root@centos7 ~ 19:31:49]# cp /usr/lib/systemd/system/sshd.service /etc/systemd/system/studyd.service
[root@centos7 ~ 19:34:24]# vim /etc/systemd/system/studyd.service 

精简配置内容:

[Unit]
Description=study server daemon 

[Service]
ExecStart=/usr/local/bin/study
 
[Install]
WantedBy=multi-user.target 

8.4 重载配置、启动并开机自启

# 重载unit配置
[root@centos7 ~ 19:35:44]# systemctl daemon-reload

# 开机自启并立即启动服务
[root@centos7 ~ 19:36:15]# systemctl enable studyd --now

# 查看服务状态
[root@centos7 ~ 19:36:40]# systemctl status studyd.service 
● studyd.service - study server daemon
   Loaded: loaded (/etc/systemd/system/studyd.service; enabled; vendor preset: disabled)
   Active: active (running) since 三 2026-07-22 19:23:12 CST; 13min ago
 Main PID: 719 (study)
   CGroup: /system.slice/studyd.service
           ├─ 719 /bin/bash /usr/local/bin/study
           └─3306 sleep 5

722 19:23:12 centos7.fangbing.cloud systemd[1]: Started study server daemon.

8.5 验证日志自动输出

[root@centos7 ~ 19:46:55]# tail -f /var/log/study.log 
2026年 07月 22日 星期三 19:46:35 CST: I'M studying [ Linux ]
2026年 07月 22日 星期三 19:46:40 CST: I'M studying [ Linux ]
2026年 07月 22日 星期三 19:46:45 CST: I'M studying [ Linux ]
2026年 07月 22日 星期三 19:46:50 CST: I'M studying [ Linux ]
2026年 07月 22日 星期三 19:46:55 CST: I'M studying [ Linux ]
2026年 07月 22日 星期三 19:47:00 CST: I'M studying [ Linux ]

效果:每5秒自动新增一行时间日志,服务永久后台守护运行。

九、总结

1. Systemd 是 CentOS7+ 统一服务管理方案,并行启动、按需加载、自动重启极大提升运维效率。

2. 服务是业务概念,守护进程是真实运行的后台进程,二者一一对应。

3. 熟练掌握 systemctl 启停、自启、禁用、重载 是运维基础能力。

ux ]
2026年 07月 22日 星期三 19:46:45 CST: I’M studying [ Linux ]
2026年 07月 22日 星期三 19:46:50 CST: I’M studying [ Linux ]
2026年 07月 22日 星期三 19:46:55 CST: I’M studying [ Linux ]
2026年 07月 22日 星期三 19:47:00 CST: I’M studying [ Linux ]


效果:每5秒自动新增一行时间日志,服务永久后台守护运行。

## 九、总结

1\. Systemd 是 CentOS7\+ 统一服务管理方案,**并行启动、按需加载、自动重启**极大提升运维效率。

2\. 服务是业务概念,守护进程是真实运行的后台进程,二者一一对应。

3\. 熟练掌握 **systemctl 启停、自启、禁用、重载** 是运维基础能力。

4\. 掌握 service 配置文件三大模块,可**自定义开发任意后台守护服务**,适配企业自定义业务进程托管需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值