systemd 登场!管好 Linux 所有后台服务
Linux 服务管理systemd 介绍基本概念CentOS 7 使用 Systemd 引导系统启动速度最快所有进程无论有无依赖关系则都是并行启动很多时候进程没有真正启动而是只有一个信号或者说是标记而已在真正利用的时候才会真正启动。Systemd为了解决上文的问题而诞生。它的目标是为系统的启动和管理提供一套完整的解决方案。服务从业务角度来称呼例如 web 服务数据库服务。守护进程daemonweb 服务器对外提供 web 服务由 web 相关的进程提供支持。以web服务为例服务web服务守护进程httpd例如# 安装软件包[rootcentos7 ~10:49:50]# yum install -y httpd# 启动服务[rootcentos7 ~11:13:41]# systemctl start httpd# 查看进程[rootcentos7 ~11:17:49]# ps -C httpd fPID TTY STAT TIME COMMAND5032? Ss0:00 /usr/sbin/httpd-DFOREGROUND5036? S0:00\_ /usr/sbin/httpd-DFOREGROUND5037? S0:00\_ /usr/sbin/httpd-DFOREGROUND5038? S0:00\_ /usr/sbin/httpd-DFOREGROUND5039? S0:00\_ /usr/sbin/httpd-DFOREGROUND5040? S0:00\_ /usr/sbin/httpd-DFOREGROUNDhttpd 服务对应的守护进程是5032、 5036 …systemd 架构unit 类型systemctl 命令用于管理不同类型的系统对象这些对象称之为units。Service unit用于定义系统服务文件扩展名为**.service**例如httpd.serviceSocket unit用于标识进程间通信用的 socket文件文件扩展名为.socketTarget unit用于模拟实现“运行级别”文件扩展名为.targetTimer unit用于管理计划任务文件扩展名为.timerDevice unit用于定义内核识别的设备文件扩展名为.deviceMount unit用于定义文件系统挂载点文件扩展名为.mountSnapshot unit管理系统快照文件扩展名为.snapshotSwap unit用于标识swap设备文件扩展名为.swapAutomount unit文件系统的自动挂载点文件扩展名为.automountPath unit用于根据文件系统上特定对象的变化来启动其他服务文件扩展名为.pathSlice unit用于资源管理文件扩展名为.slice查看 unit 列表信息# 列出状态为loaded units[rootcentos7 ~11:18:41]# systemctl list-unitssystemctl list-units命令输出说明UNIT服务单元名称。LOADsystemd是否正确解析了单元的配置并将该单元加载到内存中。ACTIVE单元的高级别激活状态。此信息表明单元是否已成功启动。SUB单元的低级别激活状态。此信息指示有关该单元的更多详细信息。信息视单元类型、 状态以及单元的执行方式而异。DESCRIPTION单元的简短描述。# -t选项查看特定类型unit 清单[rootcentos7 ~11:32:42]# systemctl list-units -t timerUNIT 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 f LOADReflects whether the unit definition was properly loaded. ACTIVEThe high-level unit activation state, i.e. generalization of SUB. SUBThe low-level unit activation state, values depend on unit type.2loadedunitslisted. Pass--allto see loaded but inactive units, too. To show all installed unit files usesystemctl list-unit-files.# 列出类型为service状态为active和inactive unit[rootcentos7 ~11:33:30]# systemctl list-units --type service --allUNIT 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 vmcoresforABRT abrt-xorg.service loaded active running ABRT Xorg log watcher...# 列出所有unit包括未loaded的unit[rootcentos7 ~11:35:04]# systemctl list-unit-filesUNIT 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 sys-fs-fuse-connections.mount static sys-kernel-config.mount static...# 查看失败的服务[rootcentos7 ~11:36:26]# systemctl --failed --type service0loadedunitslisted. Pass--allto see loaded but inactive units, too. To show all installed unit files usesystemctl list-unit-files.查看单个 unit 信息[cywcentos7 ~13:33:35]$ 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-2213:32:46 CST;23min ago Docs: man:sshd(8)man:sshd_config(5)Main PID:1227(sshd)CGroup: /system.slice/sshd.service └─1227 /usr/sbin/sshd-D关键字概述loaded单元配置文件已处理active(running)正在运行active(exited)已成功完成一次性配置active(waiting)运行中正在等待事件inactive不再运行enabled系统引导时启动disabled系统引导时不启动static无法启动依赖其他单元启动控制系统服务命令任务systemctl statusUNIT查看单元状态的详细信息。systemctl stopUNIT在运行中的系统上停止一项服务。systemctl startUNIT在运行中的系统上启动一项服务。systemctl restartUNIT在运行中的系统上重新启动一项服务。systemctl reloadUNIT重新加载运行中服务的配置文件。systemctl maskUNIT禁用服务使其无法手动启动或在系统引导时启动。systemctl unmaskUNIT使屏蔽的服务变为可用。systemctl enableUNIT将服务配置为在系统引导时启动。使用--now选项也会启动该服务。systemctl disableUNIT禁止服务在系统引导时启动。使用--now选项也会停止该服务。# 停止服务[rootcentos7 ~13:57:32]# systemctl stop sshd.service# 客户端连接测试[rootcentos7 ~13:58:30]# ssh cywcentos7 hostname# 重启服务相当于stop再start[rootcentos7 ~13:59:55]# systemctl restart sshd.service# 一般用于配置文件变动后重新加载[rootcentos7 ~14:00:56]# systemctl reload sshd.service# 重新加载服务服务对应的主进程不会重启只会重新加载一次配置文件。# 禁止服务开机自启[rootcentos7 ~14:01:38]# systemctl disable sshd.serviceRemoved symlink /etc/systemd/system/multi-user.target.wants/sshd.service.[rootcentos7 ~14:02:29]# systemctl is-enabled sshddisabled# 重启系统验证[rootcentos7 ~14:02:54]#reboot# 设置服务开机自启(由于关闭了开机自启动需要在虚拟机终端进行操作)[rootcentos7 ~14:05:41]# systemctl enable sshd.serviceCreated symlink from /etc/systemd/system/multi-user.target.wants/sshd.service to /usr/lib/systemd/system/sshd.service.[rootcentos7 ~14:06:06]# systemctl is-enable sshdUnknown operationis-enable.[rootcentos7 ~14:06:29]# systemctl is-enabled sshdenabled# 重启系统验证[rootcentos7 ~14:06:56]# reboot# 禁用服务服务被禁用后将无法start因为服务的配置文件指向/dev/null[rootcentos7 ~14:09:24]# systemctl mask sshd.serviceCreated symlink from /etc/systemd/system/sshd.service to /dev/null.[rootcentos7 ~14:10:50]# systemctl status sshd.service● sshd.service Loaded: masked(/dev/null;bad)Active: active(running)since 三2026-07-2214:09:14 CST;2min 24s ago Main PID:1196(sshd)CGroup: /system.slice/sshd.service └─1196 /usr/sbin/sshd-D7月2214:09:13 centos7.cyw systemd[1]: Starting OpenSSH server daemon...7月2214:09:14 centos7.cyw sshd[1196]: Server listening on0.0.0.0 port22.7月2214:09:14 centos7.cyw sshd[1196]: Server listening on :: port22.7月2214:09:14 centos7.cyw systemd[1]: Started OpenSSH server daemon.7月2214:09:23 centos7.cyw sshd[1690]: Accepted passwordforroot from10.1.8.1 por...h27月2214:09:26 centos7.cyw sshd[1870]: Accepted passwordforcyw from10.1.8.1 port...h27月2214:10:50 centos7.cyw systemd[1]: Currentcommandvanished from the unit file,...d. Hint: Some lines were ellipsized, use-lto showinfull.# 取消禁用[rootcentos7 ~14:11:39]# systemctl unmask sshd.serviceRemoved symlink /etc/systemd/system/sshd.service.[rootcentos7 ~14:12:55]# 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-2214:09:14 CST;3min 50s ago Docs: man:sshd(8)man:sshd_config(5)Main PID:1196(sshd)CGroup: /system.slice/sshd.service └─1196 /usr/sbin/sshd-D7月2214:09:13 centos7.cyw systemd[1]: Starting OpenSSH server daemon...7月2214:09:14 centos7.cyw sshd[1196]: Server listening on0.0.0.0 port22.7月2214:09:14 centos7.cyw sshd[1196]: Server listening on :: port22.7月2214:09:14 centos7.cyw systemd[1]: Started OpenSSH server daemon.7月2214:09:23 centos7.cyw sshd[1690]: Accepted passwordforroot from10.1.8.1 por...h27月2214:09:26 centos7.cyw sshd[1870]: Accepted passwordforcyw from10.1.8.1 port...h27月2214:10:50 centos7.cyw systemd[1]: Currentcommandvanished from the unit file,...d. Hint: Some lines were ellipsized, use-lto showinfull.unit 配置文件unit 配置文件存放在多个位置/etc /systemd/system/unit.service优先生效。一般是管理员自定义的配置。/usr/lib /systemd/system/unit.service其次生效。软件包自带的默认配置。配置文件说明示例单元文件/usr/lib/systemd/system/sshd.service说明# 标识该部分为 Unit 配置用于描述服务的基本信息、依赖关系等。 [Unit] # 服务的描述信息说明这是 OpenSSH 服务器守护进程便于管理员识别服务用途。 DescriptionOpenSSH server daemon # 指定服务的文档路径这里指向 sshd 命令的手册页man 8 sshd和配置文件的手册页man 5 sshd_config方便用户查阅帮助。 Documentationman:sshd(8) man:sshd_config(5) # 定义服务的启动顺序sshd 服务必须在 network.target网络服务就绪和 sshd-keygen.serviceSSH 密钥生成服务之后启动确保依赖的资源已准备好。 Afternetwork.target sshd-keygen.service # 表示 sshd 服务 希望 sshd-keygen.service 运行但不是强制依赖。如果 sshd-keygen.service 启动失败sshd 仍会尝试启动通常用于生成初始 SSH 密钥若密钥已存在则不影响。 Wantssshd-keygen.service # 标识该部分为 Service 配置用于定义服务的启动方式、执行命令、重启策略等。 [Service] # 定义服务的类型为 notify表示服务启动后会主动通知 systemd 自己已就绪通过 sd_notify() 函数systemd 会等待这个通知后再继续后续流程确保服务真正可用。 Typenotify # 指定环境变量文件的路径/etc/sysconfig/sshd 中通常定义 OPTIONS 等变量如额外的 sshd 启动参数这些变量会被后续的 ExecStart 引用。 EnvironmentFile/etc/sysconfig/sshd # 服务启动时执行的命令 ExecStart/usr/sbin/sshd -D $OPTIONS # /usr/sbin/sshdsshd 守护进程的可执行文件路径。 # -D表示 sshd 以非守护进程模式运行前台运行因为 systemd 通常管理前台进程便于监控。 # $OPTIONS引用 EnvironmentFile 中定义的额外参数如 -p 2222 指定端口。 # 服务重载配置时执行的命令 ExecReload/bin/kill -HUP $MAINPID # kill -HUP 发送 SIGHUP 信号给 sshd 主进程使其重新加载配置文件无需重启服务。 # $MAINPID 是 systemd 自动维护的服务主进程 ID。 # 定义服务停止时的杀死模式process 表示只杀死服务的主进程sshd 主进程其子进程如已建立的 SSH 连接会被保留避免强制中断现有连接。 KillModeprocess # 定义服务的重启策略当服务因非正常退出如崩溃、信号终止时systemd 会自动重启服务正常退出如主动停止则不重启。 Restarton-failure # 服务重启前的等待时间这里设置为 42 秒避免频繁重启导致资源耗尽。 RestartSec42s # 标识该部分为 Install 配置用于定义服务如何被 启用即系统启动时自动运行。 [Install] # 表示当系统启动到 multi-user.target多用户命令行模式非图形界面时该服务会被自动启动。这是服务器的默认运行级别确保 SSH 服务在系统启动后可用。 WantedBymulti-user.target开发一个 study 服务1.开发 studyd 服务主程序 study脚本说明这是一个无限循环的脚本每 5 秒会向/var/log/study.log文件中追加一行包含当前时间的日志内容为[时间]: IM studying [ Linux ]。[rootcentos7 ~14:17:32]# vim /usr/local/bin/study#!/bin/bash# 第一行内容是脚本的 解释器声明shebang指定该脚本使用 /bin/bash 作为解释器执行。系统会根据这一行找到对应的 shell 程序来解析后续命令。# 启动一个无限循环while 是循环关键字true 是一个永远为真的条件因此这个循环会一直执行下去直到被外部终止如 CtrlC。whiletrue# 循环体的开始标记do 和后面的 done 之间的内容是循环中重复执行的命令。do# 执行 date 命令获取当前系统时间并通过 $(...) 捕获其输出将结果赋值给变量 DATE。DATE$(date)# echo 命令输出字符串其中 $DATE 会被替换为变量的值# 是追加重定向符号将输出内容追加到 /var/log/study.log 文件中# 最终输出内容类似 Fri Oct 31 10:00:00 CST 2025: IM studying [ Linux ]。echo$DATE: IM studying [ Linux ]/var/log/study.log# 让脚本暂停执行 5 秒sleep 命令用于延迟单位默认为秒避免循环执行过快。sleep5# 循环体的结束标记与前面的 while 和 do 配合标志着一次循环的结束。done[rootcentos7 ~14:57:54]# chmod x /usr/local/bin/study2.创建 studyd 服务单元文件# 参考 sshd.service[rootcentos7 ~14:58:19]# cp /usr/lib/systemd/system/sshd.service /etc/systemd/system/studyd.service[rootcentos7 ~15:01:28]# vim /etc/systemd/system/studyd.service#[Unit]Descriptionstudy server daemon[Service]ExecStart/usr/local/bin/study[Install]WantedBymulti-user.target## 通知 systemd 读取 unit 变化[rootcentos7 ~15:06:27]# systemctl daemon-reload# 启用并启动服务[rootcentos7 ~15:06:45]# systemctl enable studyd --nowCreated symlink from /etc/systemd/system/multi-user.target.wants/studyd.service to /etc/systemd/system/studyd.service.# 查看服务状态[rootcentos7 ~15:19:08]# systemctl status studyd● studyd.service - study server daemon Loaded: loaded(/etc/systemd/system/studyd.service;enabled;vendor preset: disabled)Active: active(running)since 三2026-07-2215:19:08 CST;20s ago Main PID:4209(study)Tasks:2CGroup: /system.slice/studyd.service ├─4209 /bin/bash /usr/local/bin/study └─4238sleep57月2215:19:08 centos7.cyw systemd[1]: Started study server daemon.3,验证日志[rootcentos7 ~15:20:22]# tail -f /var/log/study.log2026年 07月22日 星期三15:21:14 CST: IM studying [ Linux ] 2026年 07月 22日 星期三 15:21:19 CST: IM studying[Linux]2026年 07月22日 星期三15:21:24 CST: IM studying [ Linux ] 2026年 07月 22日 星期三 15:21:29 CST: IM studying[Linux]2026年 07月22日 星期三15:21:34 CST: IM studying [ Linux ] 2026年 07月 22日 星期三 15:21:39 CST: IM studying[Linux]...