DevOps

Monitoring Applications with Grafana

Mayur Dabhi
Mayur Dabhi
May 23, 2026
15 min read

The server is "up", the health check returns 200, and yet users are telling you checkout takes ten seconds. You SSH in, run top, and everything looks fine right now. Without history you're guessing whether memory has been creeping up for a week or the database just had a bad five minutes.

That's the gap Grafana fills: it gives you graphs of what your system was doing before someone noticed. In this post I'll set up Prometheus, Node Exporter and Grafana with Docker Compose, expose metrics from a Node.js and a Laravel app, write the PromQL queries I actually use, and configure alerts that don't spam you.

Why Grafana?

It's open source, it runs fine on a small VPS, and it talks to a lot of backends through data source plugins: Prometheus, InfluxDB, Elasticsearch, MySQL, PostgreSQL, Loki and many more. So you can keep one UI even if your metrics and logs live in different places.

What Grafana does (and doesn't do)

The thing that confuses people first: Grafana doesn't collect or store metrics. It's a visualization and alerting layer. You point it at data sources, write queries, and it renders the results as panels on dashboards. It started in 2013 as a fork of Kibana by Torkel Ödegaard and has since grown its own alert engine and plugin ecosystem.

Because storage is someone else's job, you can swap Prometheus for InfluxDB, or use both at once, without rebuilding your dashboards from scratch.

App Server /metrics endpoint Node Exporter System metrics MySQL Exporter DB metrics Prometheus Scrapes & stores time-series data Grafana Dashboards & Alerts Alertmanager Slack / PagerDuty scrape query fire A Typical Prometheus + Grafana Stack

Grafana + Prometheus monitoring architecture

Setting Up the Monitoring Stack

Docker Compose is the quickest way to get everything running locally. This config wires up Grafana, Prometheus, and Node Exporter (for host system metrics).

1

Create docker-compose.yml

Define the three services (Grafana, Prometheus, Node Exporter) with named volumes so data survives container restarts. Change the admin password before this goes anywhere public, and pin image versions instead of latest in production.

docker-compose.yml
version: '3.8'

services:
  grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_USER=admin
      - GF_SECURITY_ADMIN_PASSWORD=mysecretpassword
      - GF_INSTALL_PLUGINS=grafana-clock-panel,grafana-piechart-panel
    volumes:
      - grafana-data:/var/lib/grafana
    depends_on:
      - prometheus

  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus-data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.retention.time=15d'
      - '--web.enable-lifecycle'

  node_exporter:
    image: prom/node-exporter:latest
    ports:
      - "9100:9100"
    volumes:
      - /proc:/host/proc:ro
      - /sys:/host/sys:ro
      - /:/rootfs:ro
    command:
      - '--path.procfs=/host/proc'
      - '--path.rootfs=/rootfs'
      - '--path.sysfs=/host/sys'
      - '--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)'

volumes:
  grafana-data:
  prometheus-data:
2

Create prometheus.yml

Tell Prometheus what to scrape and how often. Each job_name becomes a label you can filter on in queries.

prometheus.yml
global:
  scrape_interval: 15s        # How often to scrape targets
  evaluation_interval: 15s    # How often to evaluate alert rules
  scrape_timeout: 10s

scrape_configs:
  # Prometheus monitors itself
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  # Host system metrics via Node Exporter
  - job_name: 'node_exporter'
    static_configs:
      - targets: ['node_exporter:9100']

  # Your application (must expose /metrics)
  - job_name: 'myapp'
    static_configs:
      - targets: ['host.docker.internal:8080']
    metrics_path: '/metrics'
    scrape_interval: 10s
3

Start the stack

Run docker compose up -d and open Grafana at http://localhost:3000. Log in with the credentials you set in the environment variables.

4

Add Prometheus as a data source

In Grafana: Connections → Data sources → Add new data source → Prometheus. Set the URL to http://prometheus:9090 and click Save & Test.

Two Docker networking gotchas

If you type http://localhost:9090 as the data source URL, Save & Test fails with something like dial tcp [::1]:9090: connect: connection refused. Inside the Grafana container, localhost is Grafana itself. Use the Compose service name (prometheus). Also, host.docker.internal in the scrape config works out of the box on Docker Desktop but not on plain Linux. There you need extra_hosts: ["host.docker.internal:host-gateway"] on the Prometheus service, or the myapp target will show as DOWN on the Targets page.

Installing on a Linux Server

For production on Ubuntu/Debian: apt-get install -y apt-transport-https grafana after adding the Grafana APT repository. Grafana runs as a systemd service on port 3000. Prometheus binaries are available at prometheus.io/download. No package manager needed, just extract and run.

Exposing Metrics from Your Application

Prometheus pulls. It hits an HTTP endpoint on your app (usually /metrics) every scrape interval and expects the Prometheus text format back. You don't write that format by hand; a client library does it.

One thing to get right early: keep label values low-cardinality. Putting user IDs or raw URLs with IDs in a label creates a new time series per value and can blow up Prometheus memory. That's why the examples below use the route pattern (/users/:id), not the actual path.

Node.js with prom-client

metrics.js (Node.js)
const client = require('prom-client');
const express = require('express');

// Collect default Node.js metrics (heap, GC, event loop lag)
client.collectDefaultMetrics({ prefix: 'myapp_' });

// Custom counter: track every HTTP request
const httpRequestsTotal = new client.Counter({
  name: 'myapp_http_requests_total',
  help: 'Total HTTP requests',
  labelNames: ['method', 'status', 'route']
});

// Histogram: track request duration with buckets
const httpRequestDuration = new client.Histogram({
  name: 'myapp_http_request_duration_seconds',
  help: 'HTTP request latency in seconds',
  labelNames: ['method', 'route', 'status'],
  buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2, 5]
});

// Gauge: current active connections
const activeConnections = new client.Gauge({
  name: 'myapp_active_connections',
  help: 'Number of active connections'
});

const app = express();

// Middleware: record metrics for every request
app.use((req, res, next) => {
  const end = httpRequestDuration.startTimer();
  activeConnections.inc();
  res.on('finish', () => {
    const route = req.route?.path || req.path;
    httpRequestsTotal.inc({ method: req.method, status: res.statusCode, route });
    end({ method: req.method, route, status: res.statusCode });
    activeConnections.dec();
  });
  next();
});

// Prometheus scrapes this endpoint
app.get('/metrics', async (req, res) => {
  res.set('Content-Type', client.register.contentType);
  res.end(await client.register.metrics());
});

app.listen(8080);

Laravel with promphp/prometheus_client_php

In PHP-FPM every request is a fresh process, so the registry needs shared storage (Redis or APCu adapter). With the in-memory adapter your counters reset on every request and the graphs stay flat.

app/Http/Controllers/MetricsController.php
<?php

namespace App\Http\Controllers;

use Prometheus\CollectorRegistry;
use Prometheus\RenderTextFormat;

class MetricsController extends Controller
{
    public function __invoke(CollectorRegistry $registry)
    {
        $renderer = new RenderTextFormat();
        $result = $renderer->render($registry->getMetricFamilySamples());

        return response($result, 200)
            ->header('Content-Type', RenderTextFormat::MIME_TYPE);
    }
}

// In a middleware or service provider, increment counters:
$counter = $registry->getOrRegisterCounter(
    'myapp',
    'http_requests_total',
    'Total HTTP requests',
    ['method', 'status']
);
$counter->incBy(1, [$request->method(), $response->status()]);

Building Your First Dashboard

Go to Dashboards → New dashboard → Add visualization, pick the Prometheus data source, and start writing PromQL.

PromQL Queries I Reach For

Most of what you'll write is rate() over a counter, wrapped in sum by (...). Raw counter values only go up, so on their own they're useless on a graph. Keep the range window at least a few times your scrape interval: rate(x[15s]) with a 15s scrape interval often returns no data at all, because rate() needs two samples inside the window.

CPU utilization percentage per instance (idle inverted):

# Overall CPU usage %
100 - (avg by (instance) (
  rate(node_cpu_seconds_total{mode="idle"}[5m])
) * 100)

# Per-core breakdown
100 - (avg by (instance, cpu) (
  rate(node_cpu_seconds_total{mode="idle"}[5m])
) * 100)

# User vs system time
rate(node_cpu_seconds_total{mode="user"}[5m]) * 100
rate(node_cpu_seconds_total{mode="system"}[5m]) * 100

Memory usage and availability:

# Memory usage percentage
(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes)
  / node_memory_MemTotal_bytes * 100

# Absolute memory used (GB)
(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / 1e9

# Swap usage
(node_memory_SwapTotal_bytes - node_memory_SwapFree_bytes)
  / node_memory_SwapTotal_bytes * 100

HTTP request rates and error rates:

# Requests per second
rate(myapp_http_requests_total[5m])

# HTTP error rate (5xx)
rate(myapp_http_requests_total{status=~"5.."}[5m])
  / rate(myapp_http_requests_total[5m]) * 100

# Requests per second by route
sum by (route) (
  rate(myapp_http_requests_total[5m])
)

Percentile latency using histograms:

# 50th percentile (median) latency
histogram_quantile(0.50,
  sum(rate(myapp_http_request_duration_seconds_bucket[5m])) by (le)
)

# 95th percentile latency
histogram_quantile(0.95,
  sum(rate(myapp_http_request_duration_seconds_bucket[5m])) by (le)
)

# 99th percentile (catches worst-case outliers)
histogram_quantile(0.99,
  sum(rate(myapp_http_request_duration_seconds_bucket[5m])) by (le, route)
)

Using Dashboard Variables

Instead of hard-coding an instance name into every query, you define a variable like $instance that populates from Prometheus label values, then reference it in all queries. One dashboard then works for every server.

Variable Configuration (Query type)
# Variable name: instance
# Data source: Prometheus
# Query: label_values(node_cpu_seconds_total, instance)
# This populates a dropdown with all scraped instances

# Then use it in panels:
100 - (avg by (instance) (
  rate(node_cpu_seconds_total{mode="idle", instance="$instance"}[5m])
) * 100)

# Multi-value variable (select multiple instances):
rate(myapp_http_requests_total{instance=~"$instance"}[5m])

Configuring Alerts

Since Grafana 8 you can define alert rules in the Grafana UI (Grafana Alerting) instead of running a separate tool. An alert fires when a query crosses a threshold and stays there for a set duration.

Alert Fatigue is Real

If alerts fire on every small blip, people start ignoring them, including the real ones. Only alert on conditions that require human action. Use a for duration (e.g., 5 minutes) to avoid alerts firing on transient spikes. Distinguish between pages (wake someone up at 3am) and tickets (fix during business hours).

Creating an Alert Rule

Alert Rule: High CPU Usage
# Navigate to: Alerting → Alert rules → New alert rule

# Step 1: Define query (A)
# Expression:
100 - (avg by (instance) (
  rate(node_cpu_seconds_total{mode="idle"}[5m])
) * 100)

# Step 2: Set condition (B)
# Type: Classic condition
# When: avg() of A IS ABOVE 85

# Step 3: Set evaluation
# Evaluate every: 1m
# For: 5m   ← must stay above threshold for 5 min to fire

# Step 4: Set labels for routing
severity: warning
team: infrastructure

# Alert message template:
# CPU on {{ $labels.instance }} is {{ printf "%.1f" $values.A.Value }}%
# (above the 85% threshold for 5 minutes)

Setting Up Contact Points

Slack Contact Point Configuration
# Alerting → Contact points → Add contact point

# Type: Slack
# Webhook URL: https://hooks.slack.com/services/YOUR/WEBHOOK/URL
# Channel: #alerts-production

# Message template (optional, override default):
{{ define "slack.message" -}}
{{ if eq .Status "firing" }}🔴{{ else }}✅{{ end }}
*{{ .CommonLabels.alertname }}*: {{ .Status | toUpper }}
{{ range .Alerts }}
• *Instance:* {{ .Labels.instance }}
• *Severity:* {{ .Labels.severity }}
• *Value:* {{ .Annotations.value }}
{{ end }}
{{- end }}

After creating contact points, configure Notification policies to route alerts based on labels. For example, route severity=critical alerts to PagerDuty and severity=warning alerts to Slack.

Grafana Panel Types Reference

A good query in the wrong panel still hides the problem. A gauge showing "current CPU" tells you nothing about the spike ten minutes ago. Roughly how I pick:

Panel Type Best For Example Metric
Time Series Trending metrics over time, spotting spikes and patterns CPU %, requests/sec, latency
Gauge Single current value vs a min/max range with color thresholds Disk usage %, memory used
Stat Single highlighted value with optional sparkline Uptime, total requests, error count
Bar Chart Comparing values across categories or time intervals Requests by route, errors by service
Table Detailed tabular data, sortable with multiple columns Top 10 slowest endpoints, alert list
Heatmap Distribution over time: latency percentiles, request buckets Response time distribution
Pie / Donut Proportional breakdown of a total Traffic by country, errors by type
Logs Log stream from Loki with highlighting and filtering Application logs, error logs

Production Monitoring Best Practices

The test of a monitoring setup is how fast it answers "what's wrong?" at 2am. Two ideas help decide what to measure and how to lay it out.

The Four Golden Signals (Google SRE)

Google's Site Reliability Engineering book lists four signals for any user-facing service:

Dashboard Organization Strategy

Level 1: Service Overview Golden Signals: all services on one screen Level 2: API Service Routes, errors, latency Level 2: Database Queries, connections, locks Level 2: Infrastructure CPU, memory, disk, network Level 3: Per-endpoint drill-down Level 3: Slow query analysis Level 3: Host-level details

Three-tier dashboard hierarchy: overview → service → detail

Production Monitoring Checklist

  • Use the RED method for services: Rate (requests/sec), Errors (error rate), Duration (latency). It's a shorter version of the Golden Signals that fits microservices well
  • Always track p99, not just averages: Averages hide the slowest 1% of requests, and those users notice
  • Set retention deliberately: Something like 15 days of high-resolution data, with recording rules for the longer-term trends you care about
  • Use annotations for deployments: Mark every release so you can match latency changes to code changes
  • Provision dashboards as code: Store dashboard JSON in Git and load it via Grafana's provisioning directory, so nobody's hand edits in the UI quietly drift from what's in the repo
  • Test your alerts: Send test notifications to every contact point now and then. An alert that silently fails is worse than no alert
  • Keep dashboards focused: One row per concern and a dozen or so panels at most. Dense dashboards are slow to read during an incident

Recording Rules for Performance

Heavy PromQL over a 30-day range gets slow, and every open dashboard re-runs it on refresh. Recording rules compute the result on a schedule and store it as a new metric, so dashboards load faster and Prometheus does less work. Remember to add the file under rule_files in prometheus.yml, otherwise it's silently ignored.

recording_rules.yml
groups:
  - name: myapp_recording_rules
    interval: 30s
    rules:
      # Pre-compute HTTP request rate to speed up dashboards
      - record: job:myapp_http_requests_total:rate5m
        expr: sum by (job) (rate(myapp_http_requests_total[5m]))

      # Pre-compute error rate percentage
      - record: job:myapp_http_error_rate:rate5m
        expr: |
          sum by (job) (rate(myapp_http_requests_total{status=~"5.."}[5m]))
          /
          sum by (job) (rate(myapp_http_requests_total[5m])) * 100

      # Pre-compute p95 latency
      - record: job:myapp_request_duration_p95:rate5m
        expr: |
          histogram_quantile(0.95,
            sum by (le, job) (
              rate(myapp_http_request_duration_seconds_bucket[5m])
            )
          )

Useful Grafana HTTP API Commands

Task API Command
List all dashboards GET /api/search?type=dash-db
Export dashboard JSON GET /api/dashboards/uid/:uid
Import dashboard POST /api/dashboards/db
List alert rules GET /api/v1/provisioning/alert-rules
Silence an alert POST /api/alertmanager/grafana/api/v2/silences
Create annotation POST /api/annotations
Test data source GET /api/datasources/proxy/:id/api/v1/query

When I'd use this stack (and when I wouldn't)

Prometheus plus Grafana makes sense once you have more than one server or service, or you've already been burned by "it was slow yesterday and we don't know why". It's self-hosted, free, and the PromQL you learn carries over to most hosted Prometheus offerings.

It's also something you now have to run. Prometheus needs disk, upgrades and backups, and if it lives on the same box as your app, it goes down with it, which is exactly when you need it. A few cases where I'd skip it or do something else:

If you do set it up, start small: Node Exporter, one app with request rate, errors and a latency histogram, and one alert on the 5xx rate. Add panels when an incident shows you something you couldn't see, not before.

Grafana Monitoring Metrics Prometheus DevOps Observability PromQL
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.