CentOS7.9:系统服务管理结构化实战
一、项目概述
1.1 业务场景说明
CentOS 7 全部服务采用 systemd 进行管理,使用 systemctl 命令管控服务启动、停止、开机自启、查看状态;用来管理 DHCP、TFTP、vsftpd、named、ntpd、network 等服务,保障 PXE 批量装机环境所有服务开机自动运行,完成服务器自动化部署。
1.2 环境参数
项目
参数值
操作系统
CentOS Linux release 7.9‑2009
服务管理工具
systemctl(systemd)
服务文件目录
系统服务:/usr/lib/systemd/system/;用户自定义服务:/etc/systemd/system/
测试服务
dhcpd,vsftpd,named,ntpd,NetworkManager
二、systemctl 基础操作命令
2.1 启停服务命令
启动服务
systemctl start dhcpd
停止服务
systemctl stop dhcpd
重启服务
systemctl restart dhcpd
重新加载配置文件,不中断进程
systemctl reload dhcpd
2.2 查看服务运行状态
查看服务详细状态
systemctl status dhcpd
只查看运行状态(active/inactive)
systemctl is‑active dhcpd
2.3 设置开机自启与关闭开机自启
设置开机自动启动
systemctl enable dhcpd
关闭开机自启
systemctl disable dhcpd
一条命令:启动服务并设置开机自启
systemctl enable --now dhcpd
查看是否开机自启
systemctl is‑enabled dhcpd
三、查看系统服务列表
3.1 查看所有已经运行的服务
systemctl list‑units --type=service --state=running
3.2 查看全部服务(包括未启动服务)
systemctl list‑unit‑files --type=service
3.3 查看开机启动项分类
enabled:开机启动;disabled:开机禁止启动
systemctl list‑unit‑files --type=service | grep enabled
四、运行级别(target 模式)
CentOS7 放弃传统 runlevel,使用 target 模式。
查看当前默认运行级别
systemctl get‑default
切换到字符模式(multi‑user.target)
systemctl set‑default multi‑user.target
切换图形模式(graphical.target)
systemctl set‑default graphical.target
- multi‑user.target:字符界面,机房服务器标准模式;
- graphical.target:图形桌面模式。
五、自定义服务文件实战案例
创建自定义脚本服务,示例:pxe‑server.service。
5.1 编写 service 文件
vi /etc/systemd/system/pxe-server.service
写入配置:
[Unit]
Description=PXE‑Server Service
After=network.target
[Service]
Type=forking
ExecStart=/root/pxe_start.sh
ExecStop=/root/pxe_stop.sh
[Install]
WantedBy=multi‑user.target
5.2 加载新服务配置
新建或修改 service 文件后,刷新 systemd 配置:
systemctl daemon-reload
启动自定义服务并设置开机自启
systemctl enable --now pxe-server
六、屏蔽服务(彻底禁用服务)
部分服务即使设置 disable,软件安装脚本依旧会触发启动,使用 mask 彻底屏蔽。
屏蔽服务,无法手动启动
systemctl mask firewalld
解除屏蔽
systemctl unmask firewalld
七、ks.cfg 批量装机配置(适配 PXE 项目)
在 % post 脚本批量开启服务开机自启,装机完成自动启动整套 PXE 服务。
%post
systemctl enable --now dhcpd
systemctl enable --now vsftpd
systemctl enable --now named
systemctl enable --now ntpd
%end
八、高频故障总结
故障 1:设置 enable 开机自启后,重启服务器服务没有启动
- 原因 1:service 配置语法错误;
- 原因 2:依赖服务(network)启动顺序出错;
- 解决:systemctl status xxx查看日志,检查 [Unit] 段 After 字段。
故障 2:reload 命令执行失败,只能 restart - 原因:该程序不支持热加载配置;
- 解决:改用 restart 重启服务。
故障 3:服务 disable 之后,软件更新又自动开启开机项 - 原因:rpm 包脚本重新修改启动项;
- 解决:使用 systemctl mask 彻底屏蔽服务。
故障 4:自定义 service 文件修改之后配置不生效 - 原因:没有执行 daemon‑reload 刷新配置;
- 解决:执行systemctl daemon-reload,再重启服务。
