在CentOS 7上,您可以通过以下几种方式实现Apache(httpd)服务的守护和自动重启功能:
/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
chmod +x /usr/local/bin/monitor_apache.sh
crontab -e
添加以下内容:
* * * * * /usr/local/bin/monitor_apache.sh
/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
/etc/systemd/system/apache-monitor.timer
:[Unit]
Description=Run Apache monitor every minute
[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable apache-monitor.timer
systemctl start apache-monitor.timer
yum install epel-release
yum install 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
systemctl enable monit
systemctl start monit
yum install supervisor
/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
systemctl enable supervisord
systemctl start supervisord
/var/log/apache_monitor.log
或 /var/log/monit.log
您可以根据实际需求选择最适合您环境的方法。