AlertManager: roteamento avançado de alertas

AlertManager é o componente do Prometheus responsável por gerenciar alertas, agrupa notificações relacionadas, roteia para os canais corretos, silencia durante manutenções e inibe alertas redundantes. Para stacks complexas com múltiplos serviços e equipes, o AlertManager é mais poderoso que os alertas nativos do Grafana.

Adicionar AlertManager ao stack

AlertManager é um serviço separado que recebe alertas do Prometheus:

yaml
# docker-compose.yml
services:
  alertmanager:
    image: prom/alertmanager:latest
    restart: always
    volumes:
      - ./alertmanager/config.yml:/etc/alertmanager/config.yml:ro
      - alertmanager_data:/alertmanager
    command:
      - '--config.file=/etc/alertmanager/config.yml'
      - '--storage.path=/alertmanager'
      - '--web.external-url=http://localhost:9093'
    ports:
      - "127.0.0.1:9093:9093"
    networks:
      - monitoring

volumes:
  alertmanager_data:

# prometheus.yml — apontar para AlertManager:
alerting:
  alertmanagers:
    - static_configs:
        - targets: ['alertmanager:9093']

alertmanager/config.yml: roteamento

A configuração central do AlertManager: receivers, routes e agrupamento:

yaml
# alertmanager/config.yml
global:
  resolve_timeout: 5m
  telegram_api_url: 'https://api.telegram.org'

route:
  # Receiver padrão
  receiver: 'telegram-default'

  # Agrupar alertas relacionados (evita spam)
  group_by: ['alertname', 'cluster', 'service']
  group_wait: 30s           # aguardar 30s por mais alertas do mesmo grupo
  group_interval: 5m        # intervalo entre grupos
  repeat_interval: 4h       # re-notificar a cada 4h se ainda ativo

  # Roteamento por labels
  routes:
    - receiver: 'telegram-critical'
      matchers:
        - severity = critical
      group_wait: 10s        # alertas críticos: notificar mais rápido
      repeat_interval: 1h

    - receiver: 'telegram-database'
      matchers:
        - team = database
      continue: false        # parar de checar outras rotas

    - receiver: 'slack-devops'
      matchers:
        - severity =~ "warning|info"

receivers:
  - name: 'telegram-default'
    telegram_configs:
      - bot_token: 'SEU_TOKEN'
        chat_id: SEU_CHAT_ID
        message: |
          {{ range .Alerts }}
          *{{ .Status | toUpper }}* {{ .Labels.alertname }}
          {{ .Annotations.summary }}
          {{ end }}

  - name: 'telegram-critical'
    telegram_configs:
      - bot_token: 'SEU_TOKEN'
        chat_id: SEU_CHAT_ID_ONCALL

  - name: 'telegram-database'
    telegram_configs:
      - bot_token: 'SEU_TOKEN'
        chat_id: SEU_CHAT_ID_DBA

  - name: 'slack-devops'
    slack_configs:
      - api_url: 'SLACK_WEBHOOK_URL'
        channel: '#devops-alerts'

Regras de alerta no Prometheus

Defina as regras de alerta em arquivos separados e inclua no prometheus.yml:

yaml
# prometheus/alerts/services.yml
groups:
  - name: services
    interval: 30s
    rules:
      - alert: ServiceDown
        expr: up == 0
        for: 1m
        labels:
          severity: critical
          team: ops
        annotations:
          summary: "Serviço {{ $labels.job }} está down"
          description: "{{ $labels.instance }} não responde há 1+ minuto"

      - alert: HighErrorRate
        expr: |
          sum(rate(http_requests_total{status_code=~"5.."}[5m])) by (service) /
          sum(rate(http_requests_total[5m])) by (service) > 0.05
        for: 5m
        labels:
          severity: warning
          team: backend
        annotations:
          summary: "Taxa de erro alta em {{ $labels.service }}"
          description: "{{ $value | printf "%.1f" }}% das requisições com erro 5xx"

# prometheus.yml — incluir regras:
rule_files:
  - "alerts/*.yml"

Inibições: silenciar alertas redundantes

Inibições evitam spam quando um problema causa múltiplos alertas:

yaml
# alertmanager/config.yml — seção inhibit_rules
inhibit_rules:
  # Se o serviço está down (crítico), inibir alertas de warning do mesmo serviço
  - source_matchers:
      - severity = critical
    target_matchers:
      - severity = warning
    equal: ['alertname', 'instance']

  # Se o banco está down, inibir alertas de latência do banco
  - source_matchers:
      - alertname = DatabaseDown
    target_matchers:
      - team = database
    equal: ['instance']

  # Se toda a VPS está down, inibir alertas de containers individuais
  - source_matchers:
      - alertname = NodeDown
    target_matchers:
      - alertname =~ "Container.*"
    equal: ['instance']

Operações do dia a dia

API do AlertManager para gerenciar alertas e silenciamentos:

bash
# Ver alertas ativos
curl http://localhost:9093/api/v2/alerts | python3 -m json.tool

# Criar silenciamento (2 horas de manutenção)
curl -X POST http://localhost:9093/api/v2/silences \
  -H "Content-Type: application/json" \
  -d '{
    "matchers": [{"name": "instance", "value": "vps-prod-01", "isRegex": false}],
    "startsAt": "2026-06-07T22:00:00Z",
    "endsAt": "2026-06-07T23:59:00Z",
    "comment": "Manutenção programada",
    "createdBy": "ops-team"
  }'

# Listar silenciamentos ativos
curl http://localhost:9093/api/v2/silences

# Recarregar configuração sem restart
curl -X POST http://localhost:9093/-/reload

# Status do AlertManager
curl http://localhost:9093/-/ready

Não quer configurar manualmente?

Implante o VPS em menos de 5 minutos com a Runstack. Infraestrutura da OPEN Datacenter, com servidores em São Paulo.

Perguntas frequentes

Grafana Alerting (v9+): gerencia tudo no Grafana, mais simples, sem componente extra. AlertManager: mais poderoso para inibições, roteamento dinâmico por labels, múltiplos Prometheus alimentando o mesmo AlertManager. Para VPS única com Grafana: Grafana Alerting. Para múltiplos clusters ou roteamento complexo: AlertManager.

Flapping é quando um alerta fica oscilando entre firing e resolved rapidamente, gera spam de notificações. Evite com: for: 5m (alerta só dispara após 5 min contínuos), repeat_interval adequado, e thresholds menos agressivos. Se a métrica é inerentemente ruidosa: suavize com avg_over_time() antes do threshold.

group_wait: tempo que o AlertManager espera por mais alertas do mesmo grupo antes de enviar a PRIMEIRA notificação (agrupa alertas simultâneos). group_interval: intervalo entre notificações subsequentes para o mesmo grupo ativo. Para alertas críticos: group_wait curto (10-30s). Para warnings: 1-5 min.

Commite alertmanager/config.yml e prometheus/alerts/ no git. Use CI/CD para validar com amtool config check config.yml antes de deploy. Secrets (tokens, senhas): use variáveis de ambiente no docker-compose e file_sd_configs para dados sensíveis.

AlertManager não tem roteamento por horário nativo. Alternativas: (1) Pagerduty/OpsGenie como receiver (têm escalonamento e plantão nativo); (2) script Python que roteia para chat_id diferente com base no horário; (3) Grafana OnCall (open source, mais recente) que tem schedules de plantão integrado.