技能 硬件工程 Fly.io 监控与自动化部署

Fly.io 监控与自动化部署

v20260423
flyio-webhooks-events
本技能指导用户掌握Fly.io的系统监控和自动化部署流程。内容涵盖通过API轮询获取机器状态变化、设置健康检查端点、使用`jq`处理结构化日志以及在CI/CD流程中实现部署通知,旨在帮助用户确保应用的高可用性和系统可靠性。
获取技能
131 次下载
概览

Fly.io Events & Monitoring

Overview

Fly.io does not have traditional webhooks. Instead, monitor machine state changes via the Machines API, process structured logs via fly logs, and use health check endpoints for automated responses.

Instructions

Step 1: Poll Machine State Changes

// Monitor machine state transitions via Machines API
async function watchMachines(appName: string, callback: (event: MachineEvent) => void) {
  const client = new FlyClient(appName, process.env.FLY_API_TOKEN!);
  const stateCache = new Map<string, string>();

  setInterval(async () => {
    const machines = await client.listMachines();
    for (const m of machines) {
      const prev = stateCache.get(m.id);
      if (prev && prev !== m.state) {
        callback({
          machineId: m.id,
          region: m.region,
          previousState: prev,
          currentState: m.state,
          timestamp: new Date(),
        });
      }
      stateCache.set(m.id, m.state);
    }
  }, 10_000);  // Check every 10 seconds
}

interface MachineEvent {
  machineId: string;
  region: string;
  previousState: string;
  currentState: string;
  timestamp: Date;
}

Step 2: Health Check Event Handler

// Implement health check that reports machine health
// Fly.io uses this to auto-restart unhealthy machines

import express from 'express';
const app = express();

app.get('/health', async (req, res) => {
  const checks = {
    database: await checkPostgres(),
    redis: await checkRedis(),
    memory: process.memoryUsage().heapUsed < 500 * 1024 * 1024,  // < 500MB
  };

  const healthy = Object.values(checks).every(Boolean);
  res.status(healthy ? 200 : 503).json({
    status: healthy ? 'healthy' : 'unhealthy',
    region: process.env.FLY_REGION,
    machine: process.env.FLY_MACHINE_ID,
    checks,
  });
});

Step 3: Structured Log Processing

# Stream logs and process with jq
fly logs -a my-app --json | jq -c 'select(.level == "error")' | while read -r line; do
  echo "$line" >> errors.jsonl
  # Send to Slack, PagerDuty, etc.
done

# Search recent logs for specific patterns
fly logs -a my-app --no-tail | grep -i "error\|crash\|oom"

Step 4: Deployment Event Notifications

# Post-deploy notification in CI
fly deploy -a my-app && \
curl -X POST "$SLACK_WEBHOOK_URL" \
  -H "Content-Type: application/json" \
  -d "{\"text\": \"Deployed my-app to Fly.io. Status: $(fly status -a my-app --json | jq -r '.Status')\"}"

Resources

Next Steps

For performance optimization, see flyio-performance-tuning.

信息
Category 硬件工程
Name flyio-webhooks-events
版本 v20260423
大小 3.19KB
更新时间 2026-04-28
语言