如何在AWS EC2上的gunicorn服务故障时发送邮件/通知
AWS EC2上Gunicorn故障邮件通知实现方案(基于mailx/s-nail)
一、安装邮件客户端
根据EC2实例的操作系统选择对应命令:
- Amazon Linux 2/CentOS:
sudo yum install -y mailx - Ubuntu/Debian:
sudo apt update && sudo apt install -y s-nail
二、配置SMTP发送参数
以AWS SES为例(也可使用其他SMTP服务),编辑邮件客户端配置文件:
对于mailx(编辑/etc/mail.rc)
添加以下内容,替换为你的SES验证邮箱及密钥信息:
set from=your-verified-ses-email@example.com set smtp=smtp.email-smtp.us-east-1.amazonaws.com:587 set smtp-auth=login set smtp-auth-user=YOUR_SES_ACCESS_KEY set smtp-auth-password=YOUR_SES_SECRET_KEY set ssl-verify=ignore set nss-config-dir=/etc/pki/nssdb/
对于s-nail(编辑/etc/s-nail.rc)
添加以下内容:
set from=your-verified-ses-email@example.com set smtp=smtp.email-smtp.us-east-1.amazonaws.com:587 set smtp-auth=login set smtp-auth-user=YOUR_SES_ACCESS_KEY set smtp-auth-password=YOUR_SES_SECRET_KEY set ssl-verify=ignore
配置完成后测试邮件发送:
echo "测试邮件内容" | mailx -s "测试告警邮件" your-alert-email@example.com
三、实现Gunicorn故障监控与通知
方案1:定时脚本监控(适合简单场景)
- 创建监控脚本
/opt/scripts/check_gunicorn.sh:
#!/bin/bash # 替换为你的Gunicorn进程标识(如FastAPI入口文件名) APP_PROCESS="main:app" ALERT_EMAIL="your-alert-email@example.com" # 检查Gunicorn进程是否存在 if ! pgrep -f "gunicorn.*$APP_PROCESS" > /dev/null; then ALERT_CONTENT="Gunicorn服务已停止\n主机:$(hostname -f)\n时间:$(date '+%Y-%m-%d %H:%M:%S')" echo -e "$ALERT_CONTENT" | mailx -s "【紧急告警】EC2 Gunicorn服务故障" "$ALERT_EMAIL" # 可选:自动重启服务(需确保Gunicorn已注册为systemd服务) # systemctl restart gunicorn.service fi
- 给脚本添加执行权限:
chmod +x /opt/scripts/check_gunicorn.sh
- 设置crontab定时任务(每分钟检查一次):
crontab -e
添加以下内容:
* * * * * /opt/scripts/check_gunicorn.sh >> /var/log/gunicorn_monitor.log 2>&1
方案2:Systemd故障触发(实时性更高)
若Gunicorn通过systemd管理,可利用OnFailure机制实现实时通知:
- 编辑Gunicorn的systemd服务文件(如
/etc/systemd/system/gunicorn.service),在[Unit]段添加:
OnFailure=gunicorn-alert.service
- 创建告警服务文件
/etc/systemd/system/gunicorn-alert.service:
[Unit] Description=Send alert email when Gunicorn fails [Service] Type=oneshot ExecStart=/bin/bash -c 'echo -e "Gunicorn服务已停止\n主机:$(hostname -f)\n时间:$(date '+%Y-%m-%d %H:%M:%S')" | mailx -s "【紧急告警】EC2 Gunicorn服务故障" your-alert-email@example.com'
- 重新加载systemd配置并重启Gunicorn:
sudo systemctl daemon-reload sudo systemctl restart gunicorn.service
四、验证功能
手动停止Gunicorn服务测试:
sudo systemctl stop gunicorn.service
检查指定告警邮箱是否收到通知邮件,确认功能正常。
内容的提问来源于stack exchange,提问作者Shubham Singh
相关产品推荐
相关产品推荐

