🔧 DevOps

Grafana

Grafana

An open-source visualization platform. Metrics and log dashboards. Used together with Prometheus.

Detailed Explanation

Grafana is an open-source platform for visualizing metrics, logs, and trace data. Started by Torkel Odegaard in 2014, it is currently the most popular monitoring visualization tool in the world. It supports a variety of data sources and, together with Prometheus in particular, forms the core of the cloud-native monitoring stack.

Key Features

  • Dashboards: Compose panels with drag-and-drop, export/import as JSON
  • Multiple data sources: Supports Prometheus, Loki, InfluxDB, Elasticsearch, CloudWatch, and more
  • Alerting: Threshold-based alerts, Slack/PagerDuty/email integration
  • Explore: Explore data with ad-hoc queries
  • Plugins: Extend panels, data sources, and apps
  • Teams/Permissions: Access control based on organizations, teams, and folders

Grafana Stack

  • Grafana: Visualization and dashboards
  • Prometheus: Metric collection and storage
  • Loki: Log aggregation system
  • Tempo: Distributed tracing backend
  • Mimir: Long-term metric storage

Code Example

Dashboard JSON Example

{
  "dashboard": {
    "id": null,
    "uid": "api-dashboard",
    "title": "API Service Dashboard",
    "tags": ["api", "production"],
    "timezone": "browser",
    "refresh": "30s",
    "time": {
      "from": "now-1h",
      "to": "now"
    },
    "panels": [
      {
        "id": 1,
        "title": "Request Rate",
        "type": "timeseries",
        "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 },
        "datasource": { "type": "prometheus", "uid": "prometheus" },
        "targets": [
          {
            "expr": "sum(rate(http_requests_total{job=\"api\"}[5m])) by (status_code)",
            "legendFormat": "{{status_code}}"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "unit": "reqps",
            "custom": {
              "drawStyle": "line",
              "lineWidth": 2,
              "fillOpacity": 10
            }
          }
        }
      },
      {
        "id": 2,
        "title": "Response Time (p95)",
        "type": "stat",
        "gridPos": { "x": 12, "y": 0, "w": 6, "h": 4 },
        "datasource": { "type": "prometheus", "uid": "prometheus" },
        "targets": [
          {
            "expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{job=\"api\"}[5m])) by (le))",
            "legendFormat": "p95"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "unit": "s",
            "thresholds": {
              "mode": "absolute",
              "steps": [
                { "value": 0, "color": "green" },
                { "value": 0.5, "color": "yellow" },
                { "value": 1, "color": "red" }
              ]
            }
          }
        }
      },
      {
        "id": 3,
        "title": "Error Rate",
        "type": "gauge",
        "gridPos": { "x": 18, "y": 0, "w": 6, "h": 4 },
        "targets": [
          {
            "expr": "sum(rate(http_requests_total{job=\"api\",status_code=~\"5..\"}[5m])) / sum(rate(http_requests_total{job=\"api\"}[5m])) * 100",
            "legendFormat": "Error %"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "unit": "percent",
            "min": 0,
            "max": 100,
            "thresholds": {
              "steps": [
                { "value": 0, "color": "green" },
                { "value": 1, "color": "yellow" },
                { "value": 5, "color": "red" }
              ]
            }
          }
        }
      }
    ]
  }
}

Grafana Provisioning Configuration

# /etc/grafana/provisioning/datasources/prometheus.yaml
apiVersion: 1

datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
    editable: false
    jsonData:
      timeInterval: "15s"

  - name: Loki
    type: loki
    access: proxy
    url: http://loki:3100
    editable: false
    jsonData:
      derivedFields:
        - datasourceUid: tempo
          matcherRegex: "traceID=(\\w+)"
          name: TraceID
          url: "$${__value.raw}"

  - name: Tempo
    type: tempo
    access: proxy
    url: http://tempo:3200
    editable: false
---
# /etc/grafana/provisioning/dashboards/dashboards.yaml
apiVersion: 1

providers:
  - name: 'default'
    orgId: 1
    folder: 'Production'
    type: file
    disableDeletion: false
    editable: true
    options:
      path: /var/lib/grafana/dashboards

Deploying Grafana on Kubernetes

# grafana-values.yaml (Helm)
replicas: 1

persistence:
  enabled: true
  size: 10Gi

adminUser: admin
adminPassword: ${GRAFANA_ADMIN_PASSWORD}

datasources:
  datasources.yaml:
    apiVersion: 1
    datasources:
      - name: Prometheus
        type: prometheus
        url: http://prometheus-server.monitoring.svc:9090
        isDefault: true

dashboardProviders:
  dashboardproviders.yaml:
    apiVersion: 1
    providers:
      - name: 'default'
        orgId: 1
        folder: ''
        type: file
        options:
          path: /var/lib/grafana/dashboards

dashboards:
  default:
    kubernetes-cluster:
      gnetId: 6417
      revision: 1
      datasource: Prometheus
    node-exporter:
      gnetId: 1860
      revision: 31
      datasource: Prometheus

ingress:
  enabled: true
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt
  hosts:
    - grafana.example.com
  tls:
    - secretName: grafana-tls
      hosts:
        - grafana.example.com

Practical Conversation Example

SRE Engineer
"Metrics are being collected in Prometheus, but visualization is hard. I want to see the query results as graphs..."
Senior SRE
"Just integrate Grafana. Add Prometheus as a data source, build a dashboard, and you can visualize the PromQL query results. There are thousands of community-shared dashboards too, so you can import one and use it right away."
SRE Engineer
"Can I set up alerts in Grafana too?"
Senior SRE
"Yes, you can with Grafana Alerting. You set alert conditions on a panel and can send notifications to Slack or PagerDuty. That said, for complex alerts, using Prometheus Alertmanager is more flexible."

Cautions

Dashboard version control

If you modify dashboards only in the UI, no change history is kept. Store the JSON in Git and deploy it with provisioning.

Query performance

Dashboards with many heavy PromQL queries load slowly. Precompute frequently used queries with Recording Rules.

Authentication/authorization

By default, anonymous access is allowed. In production, be sure to configure authentication such as LDAP, OAuth, or SAML.

Persistence

If the Grafana database (SQLite or an external DB) is not stored on a persistent volume, dashboards disappear on restart.

Learn More