需用ps+grep确认服务完整启动命令作为pgrep唯一标识,编写循环脚本每10秒检测并重启;增强方案支持端口存活或进程+HTTP双校验;最后通过systemd设为开机自启。

在Linux服务器上,当关键服务(如Nginx、Redis或自定义Java进程)意外退出时,需通过脚本实时检测其运行状态,并在发现进程不存在时立即重启,避免业务中断。
确认服务进程标识方式
先用 ps + grep 找出目标服务的稳定识别特征:运行 ps aux | grep nginx,观察输出中唯一且不易误匹配的字段——优先选完整启动命令路径,次选带端口或配置文件路径的参数。若只用 grep nginx,可能匹配到 grep 自身进程或日志里的字符串,导致判断失真。
这一步必须完成,否则后续所有健康检查都不可靠。
编写基础循环检测脚本
新建文件 /opt/healthcheck.sh,写入以下内容:
#!/bin/bash<br>while true; do<br> if ! pgrep -f "/usr/sbin/nginx -c /etc/nginx/nginx.conf" > /dev/null; then<br> systemctl start nginx 2>/dev/null || /usr/sbin/nginx -c /etc/nginx/nginx.conf<br> fi<br> sleep 10<br>done
注意:pgrep -f 后面的字符串必须与上一步确认的完整启动命令严格一致,【哪怕多一个空格或少一个引号都会导致检测失效】。sleep 时间设为10秒是平衡资源占用与响应速度的常用值,低于5秒可能引发CPU抖动。
Linux 系统管理技能。避免权限陷阱、静默失败和常见运维错误,覆盖用户权限、文件系统、进程管理、网络配置等日常运维场景。触发词:Linux 管理、系统运维、权限、Shell 命令。
增强健壮性:加入启动失败兜底逻辑
方法一:检查端口存活(适用于监听端口的服务)
替换原 if 判断为:if ! nc -z 127.0.0.1 80 -w 2; then systemctl restart nginx; fi。nc 命令比 pgrep 更贴近真实可用性,但要求系统已安装 netcat。
方法二:组合进程+端口双校验
第一步:用 pgrep 确认进程存在;
第二步:用 curl -s --head http://127.0.0.1 | head -1 | grep "200 OK" 验证HTTP服务返回正常状态码;
第三步:仅当两步均失败时执行重启。这样能避开“进程在但服务无响应”的假死场景。
设置开机自启并后台运行
第一步:给脚本添加可执行权限 → chmod +x /opt/healthcheck.sh
第二步:创建 systemd 服务单元 → 编辑 /etc/systemd/system/healthcheck.service,填入:
[Unit]<br>Description=Service Health Monitor<br>After=network.target<br><br>[Service]<br>Type=simple<br>ExecStart=/opt/healthcheck.sh<br>Restart=always<br>RestartSec=5<br>User=root<br><br>[Install]<br>WantedBy=multi-user.target
第三步:启用并启动服务 → systemctl daemon-reload → systemctl enable healthcheck.service → systemctl start healthcheck.service。【务必执行 daemon-reload,否则 enable 操作无效】










