检查点:监控与自动重启
给应用加上健康监护。
2 天
Checkpoint: 监控与告警
你将完成什么
- 配置日志收集(PM2 日志 + 日志轮转)
- 配置应用监控(PM2 monitor / 自定义指标)
- 配置告警(邮件 / 钉钉 / 飞书)
验收标准
- 日志按日期分割
- 应用崩溃自动重启
- 关键指标(CPU、内存、错误率)可查看
核心配置
1. PM2 日志配置
// pm2.config.js
module.exports = {
apps: [{
name: 'todo-api',
script: './app.js',
instances: 'max', // 根据 CPU 核心数启动多个实例
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 3000
},
log_date_format: 'YYYY-MM-DD HH:mm:ss',
error_log: './logs/error.log',
out_log: './logs/out.log',
log_type: 'json',
merge_logs: true,
max_memory_restart: '500M', // 内存超 500M 自动重启
min_uptime: '10s',
max_restarts: 10,
autorestart: true // 崩溃自动重启
}]
};
# 启动
pm2 start pm2.config.js
# 查看日志
pm2 logs todo-api
pm2 logs todo-api --lines 100
# 日志轮转(安装 pm2-logrotate)
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:retain 7
2. 健康检查接口
// app.js
app.get('/health', (req, res) => {
res.json({
status: 'ok',
uptime: process.uptime(),
memory: process.memoryUsage(),
timestamp: new Date().toISOString()
});
});
# 定时检查
curl https://yourdomain.com/health
3. 简单告警脚本
#!/bin/bash
# alert.sh
HEALTH_URL="https://yourdomain.com/health"
WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/xxx"
response=$(curl -s -o /dev/null -w "%{http_code}" $HEALTH_URL)
if [ "$response" != "200" ]; then
curl -X POST $WEBHOOK_URL \
-H "Content-Type: application/json" \
-d '{
"msg_type": "text",
"content": {
"text": "告警:应用响应异常,状态码 '$response'"
}
}'
fi
# 加入定时任务
crontab -e
# 每 5 分钟检查一次
*/5 * * * * /var/www/todo/alert.sh
常见卡点
- 日志文件太大:配置 logrotate,按大小或日期分割。
- PM2 内存泄露:设置
max_memory_restart,定期重启。 - :设置冷却时间,同一问题 10 分钟内只告警一次。