Prometheus and Grafana Together: Setup and PromQL
How Prometheus and Grafana work together: Docker Compose lab, PromQL queries, recording rules, provisioned dashboards, alerting and scaling.
Prometheus and Grafana work together as a metrics stack: Prometheus scrapes metrics from exporters and applications, stores them as time series, and evaluates alert rules, while Grafana connects to Prometheus as a data source and turns PromQL queries into dashboards. Alertmanager handles routing alerts. You can run all of it locally with Docker Compose in minutes.
This post is a hands-on spoke of our observability tools guide. It walks through how the two tools connect, a working Docker Compose lab, the PromQL queries worth knowing, provisioning Grafana as code, and alerting. Ports, config keys and file formats were checked against the Prometheus and Grafana documentation in November 2026.
Key takeaways
- Prometheus pulls (scrapes) metrics over HTTP from
/metricsendpoints. Grafana does not collect data; it queries Prometheus. - Default ports: Prometheus 9090, Grafana 3000, Alertmanager 9093, Node Exporter 9100.
- Learn four PromQL patterns first:
rate(),sum by,histogram_quantile(), and comparison filters for alerts. - Define alerts in Prometheus rule files and route them with Alertmanager, or use Grafana Alerting. Pick one primary path so alerts are not duplicated.
- Provision Grafana data sources and dashboards from files so your setup is versioned in Git.
Who does what
| Component | Role | Default port |
|---|---|---|
| Prometheus server | Scrapes targets, stores time series, runs recording and alert rules, serves PromQL | 9090 |
| Exporters (Node Exporter, Blackbox, database exporters) | Expose metrics for systems that do not have them natively | 9100 for Node Exporter |
| Instrumented applications | Expose their own metrics with a client library | Any |
| Alertmanager | Groups, silences and routes alerts to email, Slack, PagerDuty and others | 9093 |
| Grafana | Dashboards, exploration, optional alerting, many data sources | 3000 |
Prometheus answers "what is the value of this metric over time", and Grafana answers "show it to me in a way people can read". Metrics are one signal among several; for how metrics, logs and traces fit together, read observability vs traditional monitoring.
How data flows through the stack
- An application or exporter exposes metrics in text format at
/metrics. - Prometheus scrapes each target on a schedule set by
scrape_intervaland attaches labels such asjobandinstance. - Samples land in the local time series database (TSDB). Retention defaults to 15 days unless you change
--storage.tsdb.retention.time. - Prometheus evaluates rules every
evaluation_interval. Firing alerts are sent to Alertmanager. - Grafana sends PromQL queries to the Prometheus HTTP API and draws the results.
For short-lived batch jobs that cannot be scraped, Prometheus offers the Pushgateway. Use it only for that case; it is not a general way to push metrics.
Lab: Prometheus, Node Exporter and Grafana with Docker Compose
Create a folder with three files.
docker-compose.yml
services:
prometheus:
image: prom/prometheus:latest
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.retention.time=15d
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./alerts.yml:/etc/prometheus/alerts.yml:ro
- prom-data:/prometheus
ports:
- "9090:9090"
node-exporter:
image: prom/node-exporter:latest
ports:
- "9100:9100"
grafana:
image: grafana/grafana:latest
volumes:
- ./grafana/provisioning:/etc/grafana/provisioning:ro
- grafana-data:/var/lib/grafana
ports:
- "3000:3000"
volumes:
prom-data:
grafana-data:
Pin image versions in real environments instead of latest so upgrades happen on purpose. In this lab Node Exporter runs in a container and mostly reports container-level data; on real hosts, install it as a system service or follow the Node Exporter README for running it in Docker with host mounts.
prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/alerts.yml
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ["localhost:9090"]
- job_name: node
static_configs:
- targets: ["node-exporter:9100"]
grafana/provisioning/datasources/prometheus.yml
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
Start the stack with docker compose up -d. Open http://localhost:9090/targets and confirm both targets show as UP. Then open Grafana at http://localhost:3000 (the first login is admin/admin and Grafana asks you to change it). The Prometheus data source is already there because it was provisioned from the file.
Instrument your own application
Exporters cover infrastructure. For business and request metrics, add a Prometheus client library to the application. Official or community libraries exist for Go, Java, Python, Ruby, .NET, Node.js and more. A minimal Python example with the official prometheus_client package:
from prometheus_client import Counter, Histogram, start_http_server
import random, time
REQUESTS = Counter("http_requests_total", "HTTP requests", ["path", "status"])
LATENCY = Histogram("http_request_duration_seconds", "Request latency", ["path"])
def handle(path):
with LATENCY.labels(path=path).time():
time.sleep(random.uniform(0.01, 0.3))
REQUESTS.labels(path=path, status="200").inc()
if __name__ == "__main__":
start_http_server(8000) # serves /metrics on port 8000
while True:
handle("/checkout")
Add a scrape job for app:8000 and the counter and histogram appear in Prometheus. Pick the metric type deliberately:
| Type | Use for | Query with |
|---|---|---|
| Counter | Things that only go up: requests, errors, bytes sent | rate(), increase() |
| Gauge | Values that go up and down: queue length, temperature, memory in use | The raw value, avg_over_time() |
| Histogram | Distributions such as latency or response size, aggregatable across instances | histogram_quantile() |
| Summary | Client-side quantiles for a single instance | The quantile series directly; cannot be aggregated across instances |
Keep label values bounded. Use the route template (/orders/:id) as a label, never the raw path, user ID or email address.
Finding targets automatically
Static target lists are fine for a lab. In real environments servers come and go, so Prometheus supports service discovery. Common options in scrape_configs:
file_sd_configs: read targets from JSON or YAML files that another tool (Ansible, a script) keeps up to date. Prometheus reloads them when they change.kubernetes_sd_configs: discover pods, services, endpoints and nodes from the Kubernetes API.ec2_sd_configs,azure_sd_configs,gce_sd_configs: discover cloud instances, usually filtered by tags.consul_sd_configsanddns_sd_configsfor service registries and DNS SRV records.
Discovery returns metadata labels (for example the instance's tags or a pod's namespace). Use relabel_configs to keep only the targets you want and turn useful metadata into labels such as env or team.
Probing endpoints with the Blackbox Exporter
Internal metrics tell you how a service feels from the inside. The Blackbox Exporter checks it from the outside over HTTP, HTTPS, TCP, ICMP or DNS, and reports whether the probe succeeded, how long it took and when the TLS certificate expires. A scrape job passes the URL to probe as a parameter:
- job_name: blackbox-http
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets: ["https://www.example.com"]
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: blackbox-exporter:9115
Alert on probe_success == 0 for availability, and on probe_ssl_earliest_cert_expiry - time() falling below a couple of weeks to catch certificates before they expire.
PromQL patterns worth learning first
| Goal | Query |
|---|---|
| Is the target up? | up |
| CPU busy percentage per host | 100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))) |
| Memory available percentage | 100 * node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes |
| Requests per second by status | sum by (status) (rate(http_requests_total[5m])) |
| 95th percentile latency | histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) |
| Error ratio | sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) |
A few rules keep queries correct. Apply rate() to counters (metrics ending in _total), never to gauges. Take the rate first, then aggregate with sum. Keep le in the by clause when you aggregate histogram buckets, or histogram_quantile() cannot work. The http_requests_total and http_request_duration_seconds names are common conventions from client libraries; check what your application actually exports.
Recording rules for heavy queries
If a dashboard panel runs an expensive query on every refresh, precompute it with a recording rule:
groups:
- name: http-recording
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
Grafana then queries job:http_requests:rate5m, which is cheap.
Building dashboards in Grafana
In Grafana, create a dashboard, add a visualization, choose the Prometheus data source and paste a query. A few habits make dashboards useful during an incident:
- Use variables. A
$instancevariable built fromlabel_values(up, instance)lets one dashboard cover every host. - Set units. Percent, bytes, seconds and requests per second make panels readable at a glance.
- Put the user-facing signals at the top. Request rate, errors and latency first; CPU and memory below.
- Start from community dashboards. Grafana's dashboard library has ready-made boards, such as the widely used "Node Exporter Full" (ID 1860). Import one, then trim it to what you need.
For dashboard ideas by audience and use case, see real-time monitoring dashboards to build.
Dashboards as code
Clicking dashboards together works for exploration. For shared environments, export the dashboard JSON, commit it to Git, and provision it with a dashboard provider file:
apiVersion: 1
providers:
- name: default
folder: Infrastructure
type: file
options:
path: /etc/grafana/provisioning/dashboards/json
Grafana loads every JSON file in that path at startup and watches for changes. Teams that manage infrastructure with Terraform can also use the Grafana Terraform provider.
Alerting
Write alert rules in Prometheus and let Alertmanager route them. A small alerts.yml:
groups:
- name: node-alerts
rules:
- alert: InstanceDown
expr: up == 0
for: 5m
labels:
severity: critical
annotations:
summary: "{{ $labels.instance }} is down"
- alert: HighCpu
expr: 100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))) > 90
for: 15m
labels:
severity: warning
annotations:
summary: "CPU above 90% on {{ $labels.instance }}"
The for clause stops brief spikes from paging anyone. To deliver alerts, add an alerting block in prometheus.yml pointing at Alertmanager on port 9093, and configure receivers in Alertmanager.
Grafana Alerting is the alternative. It can alert on any Grafana data source and is managed in the UI or by provisioning. Both work; running both on the same signals usually means duplicate pages. For which alerts to start with, read 10 monitoring alerts every DevOps team should configure.
Routing alerts with Alertmanager
Alertmanager groups related alerts, waits briefly so one outage does not send fifty messages, and sends each group to the right receiver. A small alertmanager.yml:
route:
receiver: team-email
group_by: [alertname, instance]
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
- matchers:
- severity="critical"
receiver: oncall-pager
receivers:
- name: team-email
email_configs:
- to: [email protected]
- name: oncall-pager
webhook_configs:
- url: http://pager-bridge.internal/alert
SMTP settings for email go in the global section. Silences, created in the Alertmanager UI or with amtool, mute alerts during planned maintenance. Inhibition rules suppress lower-severity alerts when a related critical one is already firing, for example hiding "high latency" while "instance down" is active.
Laying out a dashboard: RED and USE
Two well-known methods give a starting layout. For request-driven services, the RED method tracks Rate, Errors and Duration. For resources such as hosts, disks and queues, the USE method tracks Utilisation, Saturation and Errors.
| Row | Panel | Example query |
|---|---|---|
| Service (RED) | Request rate | sum(rate(http_requests_total[5m])) |
| Service (RED) | Error ratio | sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) |
| Service (RED) | p95 latency | histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) |
| Host (USE) | CPU utilisation | 1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) |
| Host (USE) | Saturation (load per CPU) | node_load1 / count by (instance) (node_cpu_seconds_total{mode="idle"}) |
| Host (USE) | Disk space used | 1 - node_filesystem_avail_bytes / node_filesystem_size_bytes |
Put the RED row at the top. If request rate, errors and latency look normal, users are probably fine, and the USE rows explain why things are slow when they are not.
Securing Prometheus and Grafana
- Do not expose Prometheus or exporters to the internet. Their endpoints have no authentication by default. Keep them on private networks or behind a reverse proxy.
- Turn on TLS and basic auth where needed. Prometheus and the official exporters accept a web configuration file (
--web.config.file) for TLS and basic authentication. - Change Grafana's admin password at first login and connect Grafana to your identity provider (LDAP, OAuth or SAML, depending on edition) so people use named accounts.
- Use Grafana roles and folder permissions so viewers cannot edit production dashboards or data sources.
- Keep secrets out of dashboards and Git. Data source passwords belong in environment variables or a secret store referenced from provisioning files.
Monitoring Kubernetes with the same stack
On Kubernetes, most teams install the kube-prometheus-stack Helm chart from the prometheus-community repository. It deploys the Prometheus Operator, Prometheus, Alertmanager, Grafana, Node Exporter and kube-state-metrics with default dashboards and rules. Targets are then declared with ServiceMonitor and PodMonitor resources instead of static configs.
Scaling beyond one Prometheus server
A single Prometheus server keeps data locally and is not clustered. When you need long retention, a global view across clusters, or high availability, common options are:
- Run two identical Prometheus servers for HA and let Alertmanager deduplicate alerts.
- Use
remote_writeto send samples to long-term storage such as Thanos, Grafana Mimir, Cortex or a managed service. - Use federation sparingly, for pulling aggregated series from lower-level servers.
Watch label cardinality as you grow. A label holding user IDs or full URLs creates a new series per value and can exhaust memory. Our post on observability challenges and solutions covers cardinality and cost.
Where Prometheus and Grafana fit among other options
| Option | Model | Good fit when |
|---|---|---|
| Prometheus + Grafana (self-managed) | Open source, you run it | You want control, Kubernetes-native metrics and no per-host licence |
| Managed Prometheus services | PromQL-compatible storage run by a cloud provider | You like PromQL but do not want to operate storage and HA |
| Grafana Cloud | Hosted Grafana with metrics, logs and traces backends | You want the same tools without running them |
| Commercial APM suites | Agent-based, SaaS | You need deep tracing and code-level profiling out of the box |
Many teams mix them: Prometheus for infrastructure and Kubernetes metrics, plus a tracing backend for request flows. Our observability tools guide compares the wider set.
Common mistakes
- Using
rate()on a gauge, or summing before taking the rate. - A range window shorter than about four scrape intervals, which produces gaps.
- Leaving Grafana's default admin password or exposing Prometheus to the internet without authentication.
- Dashboards with fifty panels that nobody reads during an incident.
- Alerting on causes (high CPU) instead of symptoms users feel (errors, latency).
FAQ
Do I need both Prometheus and Grafana?
Prometheus can run alone and has a basic expression browser, but Grafana gives you real dashboards, variables and sharing. Most teams run both: Prometheus stores and alerts, Grafana visualises.
What ports do Prometheus and Grafana use?
Prometheus listens on 9090, Grafana on 3000, Alertmanager on 9093 and Node Exporter on 9100 by default. You can change each with a flag or configuration setting.
Does Prometheus push or pull metrics?
Prometheus pulls. It scrapes HTTP /metrics endpoints on a schedule. The Pushgateway exists for short-lived batch jobs that finish before a scrape could happen.
How long does Prometheus keep data?
The default local retention is 15 days. Change it with --storage.tsdb.retention.time or a size limit, or send data to long-term storage with remote_write.
Should I use Prometheus Alertmanager or Grafana Alerting?
Either works. Alertmanager suits teams that keep rules in Git next to Prometheus. Grafana Alerting suits teams that alert across several data sources. Choose one primary path to avoid duplicate alerts.
How do I add Prometheus as a data source in Grafana?
In Grafana go to Connections, add a Prometheus data source and enter its URL, such as http://prometheus:9090. Or provision it with a YAML file in the provisioning/datasources folder.
What is PromQL?
PromQL is the Prometheus query language. It selects time series by metric name and labels, and applies functions such as rate, sum and histogram_quantile to calculate rates, totals and percentiles.
Practise with a trainer
Our Prometheus and Grafana training covers exporters, PromQL, alerting and Kubernetes monitoring, in our Kharadi, Pune classroom or live online. To check your knowledge, try 80+ Prometheus interview questions and the scenario-based Prometheus questions.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0