HANDS-ON LAB Intermediate

Uptime Monitoring with Prometheus Blackbox Exporter: HTTP Probes & Anti-Flapping

Configure external HTTP/HTTPS health checks, monitor SSL certificate expiration dates, and build flap-resistant Alertmanager rules.

Vibe DevOps·· ~13 min read
PrometheusBlackbox ExporterAlertmanagerDockerPython

Key Takeaways & Prerequisites

  • Whitebox monitoring (internal metrics) cannot verify whether actual external end-users can resolve DNS, establish TLS, or receive 200 OK responses.
  • Prometheus Blackbox Exporter probes endpoints externally via HTTP, HTTPS, TCP, DNS, and ICMP, reporting latency breakdowns across connection phases.
  • Configure probe_http_status_codes and fail_if_not_matches_regexp to validate that returned HTML/JSON payloads contain expected tokens.
  • Route alerts through Alertmanager with group_by, group_wait, and repeat_interval to prevent notification floods during network incidents.

Architecture & Execution Flow

  1. 01 →Blackbox ExporterHTTP/HTTPS/TCP endpoint probing
  2. 02 →Latency BreakdownDNS, TLS, connect, processing times
  3. 03 →Prometheus Rulesprobe_success == 0 alerting
  4. 04 →Alertmanager RoutingGrouped notifications to Slack/Telegram
Table of Contents

In distributed systems engineering, one of the most frustrating scenarios for an SRE team is the "all green" paradox: internal Grafana dashboards show all microservices operating normally, CPU and memory utilization remain within baseline, application runtimes report zero unhandled exceptions—yet customers report that the service is completely unreachable or returning network timeouts.

This discrepancy highlights the fundamental divide between Whitebox Monitoring and Blackbox Monitoring[5]: - Whitebox monitoring: Collects internal telemetry directly from an application runtime via endpoints such as /metrics (e.g., Prometheus client libraries, JVM runtime stats, connection pool saturation). It explains why an internal component is failing, but cannot verify whether external network paths can reach the service. - Blackbox monitoring: Evaluates service availability and degradation strictly from an external perspective, without visibility into underlying application code. The prober issues real network requests (HTTP GET/POST, TCP handshakes, DNS resolutions, ICMP pings) that traverse the complete production ingress path: external DNS resolvers, transit firewalls, Web Application Firewalls (WAFs), Ingress Controllers, load balancers, and edge TLS termination layers.

If an SSL certificate expires, port 443 is blocked by a modified Security Group, or an Nginx upstream worker deadlocks, whitebox metrics remain entirely blind to the incident. This guide provides an end-to-end implementation for deploying Prometheus Blackbox Exporter with Alertmanager to monitor uptime, track phase-level HTTP latency, detect impending TLS expiration, and configure anti-flapping alerting rules to prevent on-call alert fatigue.

Scope and Validation: All configuration files (blackbox.yml, prometheus.yml, alert_rules.yml, alertmanager.yml) and probe scenarios detailed in this guide have been validated for syntax compliance using PyYAML and AST parsing, and verified via loopback probing on a Linux host. Docker Compose workflows and Prometheus queries represent production-ready patterns suitable for local testing or production clusters.

1. Blackbox Exporter Architecture and the Stateless Probe Pattern

Unlike standard exporters (such as Node Exporter or MySQL Exporter, which run as persistent background daemons collecting host-local metrics), Blackbox Exporter operates as a stateless probe proxy[1].

Blackbox Exporter does not run an internal scheduler or cache target responses. Instead, it exposes a single HTTP endpoint at /probe. When Prometheus issues a scrape request to /probe?target=https://vibedevops.net&module=http_2xx, Blackbox Exporter executes the following lifecycle:

  1. Loads the specified module (http_2xx) to parse probe definitions: HTTP methods, supported protocol versions, custom headers, SSL verification parameters, and response body regex matchers.
  2. Initiates an active network request to the specified target (https://vibedevops.net).
  3. Instruments connection lifecycle timings across each discrete phase:
  4. DNS resolution latency (probe_dns_lookup_time_seconds)
  5. TCP handshake latency (probe_tcp_connect_time_seconds)
  6. TLS negotiation duration (probe_tls_handshake_seconds)
  7. Time to First Byte (TTFB) (probe_http_duration_seconds{phase="waiting"})
  8. Total probe duration (probe_duration_seconds)
  9. Emits the collected timings as Prometheus metrics within the scrape response payload. The primary health indicator is probe_success (yielding 1 if all module assertions pass, or 0 on any assertion failure).

Because the exporter is stateless, a single Blackbox Exporter container can probe hundreds or thousands of external endpoints and IP addresses across hybrid or multi-cloud topologies.

2. Production-Grade blackbox.yml Configuration

Create a blackbox.yml configuration file to declare active probing modules:

modules:
  http_2xx:
    prober: http
    timeout: 5s
    http:
      valid_http_versions: ["HTTP/1.1", "HTTP/2.0"]
      valid_status_codes: [200, 204]
      method: GET
      headers:
        User-Agent: "VibeDevOps-Blackbox-Monitor/1.0"
        Accept: "text/html,application/xhtml+xml,application/json"
      follow_redirects: true
      fail_if_body_matches_regexp:
        - "(?i)(error 5[0-9]{2}|database connection error|internal server error)"
      tls_config:
        insecure_skip_verify: false

  http_api_post:
    prober: http
    timeout: 5s
    http:
      method: POST
      headers:
        Content-Type: "application/json"
        User-Agent: "VibeDevOps-Blackbox-Monitor/1.0"
      body: '{"action":"healthcheck"}'
      valid_status_codes: [200, 201]

  tcp_connect:
    prober: tcp
    timeout: 5s

  icmp_ping:
    prober: icmp
    timeout: 3s

Key Architectural Considerations:

  • fail_if_body_matches_regexp: In production, failed database pools or uncaught application exceptions often result in upstream reverse proxies returning an HTTP 200 OK wrapped around a custom HTML error page. This configuration forces probe failure (probe_success = 0) whenever common database error strings or 50x indicators appear in the response payload.
  • Custom User-Agent: By default, Blackbox Exporter identifies itself as Go's standard HTTP client (Go-http-client/1.1). Enterprise WAFs (such as Cloudflare, AWS WAF, or strict ModSecurity profiles) routinely block or rate-limit this header as automated bot traffic. Defining an explicit, unique User-Agent simplifies rule whitelisting and access-log attribution.
  • insecure_skip_verify: false: Enforces strict TLS certificate validation against trusted root CAs. If a certificate is self-signed, untrusted, or expired, the probe fails automatically.

3. Prometheus Scrape Configuration and Relabeling Mechanics

The primary operational challenge when integrating Prometheus with Blackbox Exporter stems from target routing: Prometheus must scrape the exporter instance (blackbox-exporter:9115), but the measured target is an arbitrary list of external URLs (https://vibedevops.net, https://api.example.com).

Defining individual scrape targets manually creates unmaintainable configurations. Prometheus handles this decoupling through relabel_configs[3]:

global:
  scrape_interval: 30s
  evaluation_interval: 30s

rule_files:
  - "/etc/prometheus/alert_rules.yml"

alerting:
  alertmanagers:
    - static_configs:
        - targets:
            - "alertmanager:9093"

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]

  - job_name: "blackbox-http"
    metrics_path: /probe
    params:
      module: [http_2xx]
    static_configs:
      - targets:
          - "https://vibedevops.net"
          - "https://vibedevops.net/thuc-chien/"
          - "https://api.example.com/health"
    relabel_configs:
      # 1. Map original target (__address__) to __param_target query parameter
      - source_labels: [__address__]
        target_label: __param_target

      # 2. Assign the target URL to the instance label for dashboard and alert readability
      - source_labels: [__param_target]
        target_label: instance

      # 3. Rewrite scrape address (__address__) to route to Blackbox Exporter service
      - target_label: __address__
        replacement: "blackbox-exporter:9115"

Label Mutation Flow:

  1. Target URLs declared in static_configs (e.g., https://vibedevops.net) are stored in the internal __address__ label.
  2. Step 1: The relabel rule copies this value to __param_target. Prometheus automatically converts any label with the __param_<name> syntax into an HTTP query parameter: ?target=https://vibedevops.net.
  3. Step 2: The target URL is copied to the instance label. Without this step, all resulting metrics would inherit instance="blackbox-exporter:9115", making it impossible to correlate metrics with specific endpoints.
  4. Step 3: The __address__ label is rewritten to blackbox-exporter:9115, which sets the actual network socket Prometheus connects to for the scrape operation.

The resulting HTTP scrape matches: http://blackbox-exporter:9115/probe?module=http_2xx&target=https%3A%2F%2Fvibedevops.net

4. Alerting Rules: Failure Thresholds, Latency Degradation, and SSL Expiration

Create /etc/prometheus/alert_rules.yml to define production alerting logic:

groups:
  - name: blackbox_alerts
    rules:
      - alert: BlackboxProbeFailed
        expr: probe_success == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Endpoint không thể truy cập: {{ $labels.instance }}"
          description: "Blackbox probe thất bại liên tục trong hơn 2 phút đối với {{ $labels.instance }}. Kiểm tra mạng, DNS hoặc ứng dụng."
          runbook_url: "https://vibedevops.net/cheatsheets/007-nginx-reverse-proxy"

      - alert: SSLCertificateExpiringSoon
        expr: (probe_ssl_earliest_cert_expiry - time()) / 86400 < 14
        for: 1h
        labels:
          severity: warning
        annotations:
          summary: "Chứng chỉ SSL sắp hết hạn: {{ $labels.instance }}"
          description: "Chứng chỉ TLS của {{ $labels.instance }} sẽ hết hạn trong vòng dưới 14 ngày (còn lại: {{ $value | printf \"%.1f\" }} ngày)."
          runbook_url: "https://vibedevops.net/thuc-chien/tls-certificate-het-han-openssl-systemd-timer"

      - alert: HTTPHighLatency
        expr: probe_duration_seconds > 2
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Độ trễ HTTP cao bất thường: {{ $labels.instance }}"
          description: "Thời gian hoàn thành probe HTTP vượt quá 2 giây liên tục trong 5 phút (hiện tại: {{ $value | printf \"%.2f\" }}s)."

Critical Operational Thresholds:

  • Hysteresis and for: 2m: Over public WAN connections, transient packet drops and route flaps are expected baseline behavior. Firing alerts immediately (for: 0s) leads to alert fatigue from transient network blips. Setting for: 2m requires at least 4 consecutive probe failures at a 30-second scrape interval before triggering an alert state, ensuring only actionable incidents wake on-call engineers.
  • probe_ssl_earliest_cert_expiry: This metric returns the Unix timestamp of the earliest expiring certificate in the chain. The PromQL expression (metric - time()) / 86400 tracks the remaining validity in days, eliminating the need for external cron jobs or custom TLS check scripts.

5. Alertmanager Configuration: Mitigating Alert Storms and Flapping

During broad infrastructure outages (such as edge transit failure or Ingress crash), downstream alerts fire simultaneously: synthetic probes fail, latency metrics breach thresholds, and internal APIs drop. Without structured alert deduplication, on-call teams are flooded with redundant notifications.

The following alertmanager.yml implements production alert grouping, deduplication, and inhibition[4]:

global:
  resolve_timeout: 5m

route:
  group_by: ["alertname", "cluster", "service"]
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 4h
  receiver: "devops-default-webhook"
  routes:
    - match:
        severity: critical
      receiver: "devops-critical-channel"
      repeat_interval: 1h

inhibit_rules:
  - source_match:
      severity: "critical"
      alertname: "BlackboxProbeFailed"
    target_match:
      severity: "warning"
      alertname: "HTTPHighLatency"
    equal: ["instance"]

receivers:
  - name: "devops-default-webhook"
    webhook_configs:
      - url: "http://alert-receiver.internal:8080/alerts"
        send_resolved: true

  - name: "devops-critical-channel"
    webhook_configs:
      - url: "http://alert-receiver.internal:8080/critical-alerts"
        send_resolved: true

Noise Reduction Mechanisms:

  1. group_wait: 30s: When an alert is detected, Alertmanager buffers notifications for 30 seconds to aggregate other alerts matching the same group_by criteria. This consolidates cascading failures into a single digest rather than dispatching 10 separate alerts.
  2. repeat_interval: 4h: While an incident remains actively firing and unacknowledged, repetitive alerts are suppressed. Alertmanager re-notifies only once every 4 hours if the root cause remains unresolved.
  3. inhibit_rules (Inhibition): If an endpoint is completely down (BlackboxProbeFailed), latency alerts are redundant and unhelpful. The inhibition rule instructs Alertmanager: If a Critical BlackboxProbeFailed alert is firing on instance X, immediately suppress any Warning HTTPHighLatency alert on that same instance X. This ensures incident response channels stay focused on the primary failure.

6. Standalone Lab Deployment via Docker Compose

To test and validate this stack in an isolated local or cloud environment, use the following docker-compose.yml:

services:
  blackbox-exporter:
    image: prom/blackbox-exporter:v0.25.0
    container_name: blackbox-exporter
    restart: unless-stopped
    ports:
      - "9115:9115"
    volumes:
      - ./blackbox.yml:/etc/blackbox_exporter/config.yml:ro
    command:
      - "--config.file=/etc/blackbox_exporter/config.yml"

  prometheus:
    image: prom/prometheus:v2.54.1
    container_name: prometheus
    restart: unless-stopped
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - ./alert_rules.yml:/etc/prometheus/alert_rules.yml:ro
      - prometheus_data:/prometheus
    command:
      - "--config.file=/etc/prometheus/prometheus.yml"
      - "--storage.tsdb.path=/prometheus"
      - "--web.enable-lifecycle"
    depends_on:
      - blackbox-exporter

  alertmanager:
    image: prom/alertmanager:v0.27.0
    container_name: alertmanager
    restart: unless-stopped
    ports:
      - "9093:9093"
    volumes:
      - ./alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
      - alertmanager_data:/alertmanager
    command:
      - "--config.file=/etc/alertmanager/alertmanager.yml"
      - "--storage.path=/alertmanager"

volumes:
  prometheus_data:
  alertmanager_data:

Verification Workflow:

Start the monitoring stack:

docker compose up -d

Verify Blackbox Exporter functionality directly using curl:

curl -s "http://localhost:9115/probe?target=https://vibedevops.net&module=http_2xx" | grep -E "^probe_(success|duration_seconds|http_status_code|ssl_earliest_cert_expiry)"

Expected output for a healthy target:

probe_duration_seconds 0.1842
probe_http_status_code 200
probe_ssl_earliest_cert_expiry 1.7824e+09
probe_success 1

Verify scrape target status via the Prometheus HTTP API:

curl -s "http://localhost:9090/api/v1/targets" | jq '.data.activeTargets[] | {labels: .labels, health: .health}'

Query the probe status across all monitored domains:

curl -s "http://localhost:9090/api/v1/query?query=probe_success" | jq '.data.result[] | {instance: .metric.instance, status: .value[1]}'

If an endpoint returns status: "0", Prometheus registers a connection or assertion failure, transitions the rule to PENDING, and escalates to FIRING once the 2-minute threshold passes.

7. Production Pitfalls and Edge Cases

Pitfall 1: WAF and Bot Mitigation False Positives

  • Symptom: Probing an endpoint returns HTTP 403 Forbidden or 503 Service Temporarily Unavailable, while desktop browsers access the application normally.
  • Root Cause: Go's underlying HTTP client lacks standard browser headers, causing edge bot management solutions to classify probe traffic as malicious scrapers.
  • Mitigation: Define a custom User-Agent within blackbox.yml and establish explicit bypass rules on edge WAFs (e.g., Cloudflare WAF Custom Rules) matching the static egress IP of the monitoring host.

Pitfall 2: Stale DNS Records Post-Migration

  • Symptom: DNS records are updated to point to a new target IP, and external traffic migrates cleanly, yet Blackbox Exporter continues to probe and fail against the deprecated IP.
  • Root Cause: Container runtimes or host-level systemd-resolved instances often cache A/AAAA records beyond their specified TTL, or HTTP keepalive reuse prevents socket re-creation.
  • Mitigation: Set preferred_ip_protocol: "ip4" in blackbox.yml and ensure local caching resolvers honor upstream TTL ceilings. During migrations, restart the Blackbox Exporter container to force a purge of its HTTP connection pool.

Pitfall 3: SNI Mismatches in Shared Multi-Tenant Ingress

  • Symptom: Probing virtual hosts that share an edge IP fails the TLS handshake or returns expiration metrics for an incorrect fallback certificate.
  • Mitigation: In the tls_config block of the prober module, explicitly configure server_name: "yourdomain.com" when probing by IP or through an intermediate proxy. This guarantees that Blackbox Exporter populates the correct Server Name Indication (SNI) extension in the TLS Client Hello.

8. Teardown and Cost Modeling

To tear down the local lab and purge associated volumes:

docker compose down -v

Infrastructure Cost Analysis:

  • Self-Hosted Architecture: The combined footprint of Prometheus, Blackbox Exporter, and Alertmanager is minimal. A lightweight virtual instance (1 vCPU, 2 GB RAM, 20 GB SSD) costing $4–$6/month (e.g., Hetzner, DigitalOcean, or AWS Lightsail) can comfortably probe hundreds of endpoints every 30 seconds at < 5% baseline CPU utilization.
  • Commercial SaaS Comparison (Datadog Synthetics / Pingdom): SaaS alternatives typically charge $15–$40/month for entry-level tiers (capped at 10–20 checks). Self-hosting Blackbox Exporter reduces synthetic monitoring costs by over 80% while providing full metric ownership and unlimited custom alerting logic.

9. References

Technical references and documentation versions verified against upstream releases:

  • [1] Prometheus Documentation: Blackbox Exporter Repository & Prober Specification - https://github.com/prometheus/blackbox_exporter
  • [2] Prometheus Documentation: Scrape Configuration & Relabeling - https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config
  • [3] Prometheus Documentation: Alerting Rules Best Practices - https://prometheus.io/docs/practices/alerting/
  • [4] Prometheus Alertmanager: Configuration & Inhibit Rules - https://prometheus.io/docs/alerting/latest/configuration/
  • [5] Google SRE Book: Chapter 6 - Monitoring Distributed Systems & The Philosophy of Alerting - https://sre.google/sre-book/monitoring-distributed-systems/
Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs