插件窝 干货文章 Centos7 apache守护(定时检测apache状态)

Centos7 apache守护(定时检测apache状态)

Apache monitor systemctl httpd 407    来源:    2025-05-11

CentOS 7 Apache守护脚本(定时检测Apache状态)

在CentOS 7上,您可以通过以下几种方式实现Apache(httpd)服务的守护和自动重启功能:

方法一:使用Shell脚本 + crontab

  1. 创建监控脚本 /usr/local/bin/monitor_apache.sh
#!/bin/bash

# 检查Apache是否运行
if ! systemctl is-active --quiet httpd; then
    # 记录重启日志
    echo "$(date) - Apache is down, attempting to restart..." >> /var/log/apache_monitor.log
    # 尝试重启Apache
    systemctl restart httpd

    # 检查重启是否成功
    if systemctl is-active --quiet httpd; then
        echo "$(date) - Apache restarted successfully" >> /var/log/apache_monitor.log
    else
        echo "$(date) - Failed to restart Apache" >> /var/log/apache_monitor.log
    fi
fi
  1. 给脚本执行权限:
chmod +x /usr/local/bin/monitor_apache.sh
  1. 添加crontab任务(每分钟检查一次):
crontab -e

添加以下内容:

* * * * * /usr/local/bin/monitor_apache.sh

方法二:使用systemd服务单元

  1. 创建服务文件 /etc/systemd/system/apache-monitor.service
[Unit]
Description=Apache Monitor Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/monitor_apache.sh
Restart=always
RestartSec=60

[Install]
WantedBy=multi-user.target
  1. 创建定时器文件 /etc/systemd/system/apache-monitor.timer
[Unit]
Description=Run Apache monitor every minute

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min

[Install]
WantedBy=timers.target
  1. 启用并启动服务:
systemctl daemon-reload
systemctl enable apache-monitor.timer
systemctl start apache-monitor.timer

方法三:使用Monit监控工具

  1. 安装Monit:
yum install epel-release
yum install monit
  1. 配置Monit /etc/monit.d/apache
check process httpd with pidfile /var/run/httpd/httpd.pid
    start program = "/usr/bin/systemctl start httpd"
    stop program = "/usr/bin/systemctl stop httpd"
    if failed host 127.0.0.1 port 80 protocol http then restart
    if cpu > 60% for 5 cycles then alert
    if cpu > 80% for 5 cycles then restart
    if memory > 500 MB for 5 cycles then restart
    if 3 restarts within 5 cycles then timeout
  1. 启动Monit服务:
systemctl enable monit
systemctl start monit

方法四:使用Supervisor

  1. 安装Supervisor:
yum install supervisor
  1. 配置 /etc/supervisord.d/apache.ini
[program:httpd]
command=/usr/sbin/httpd -DFOREGROUND
autostart=true
autorestart=true
startretries=3
stderr_logfile=/var/log/httpd/error.log
stdout_logfile=/var/log/httpd/access.log
  1. 启动Supervisor:
systemctl enable supervisord
systemctl start supervisord

注意事项

  1. 确保脚本和日志文件有适当的权限
  2. 定期检查日志文件 /var/log/apache_monitor.log/var/log/monit.log
  3. 根据您的服务器负载调整检查频率
  4. 对于生产环境,建议使用方法三(Monit)或方法四(Supervisor),它们提供更完善的监控功能

您可以根据实际需求选择最适合您环境的方法。