Prometheus Rules
NotesAlerts are defined as Prometheus rules. (Not to be confused with Alertmanager, in the next section, which only decides what to do once an alert fires.)
What is a Prometheus rule? It’s a query with a condition. For example, this query returns a result only when the home page has had more than 10 views in the last five minutes:
increase(home_page_hits_total[5m]) > 10When a rule’s query returns a result, the alert fires.
Create a directory for rules, next to prometheus.yml:
mkdir ~/volumes/prometheus/rulesAnd add a rules file, with two alerts:
groups:
- name: fastapi
rules:
- alert: HomePageBusy
expr: increase(home_page_hits_total[5m]) > 10
for: 1m
labels:
severity: warning
annotations:
summary: The home page has been viewed more than 10 times in 5 minutes
- alert: FastAPIDown
expr: up{job="fastapi"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: Prometheus can't scrape the FastAPI applicationHomePageBusyis a simple example, using the custom counter.FastAPIDownis the most useful alert of all: Prometheus setsupto0for any target it can’t scrape, so this fires if the application stops responding.for: 1mmeans the condition must hold for a minute before the alert fires, which avoids alerts for brief blips.labelsare used by Alertmanager to decide where alerts go, andannotationsdescribe the alert.
Update prometheus.yml to load every file in the rules directory. The directory is mounted at /etc/prometheus in the container:
rule_files:
- /etc/prometheus/rules/*.ymlCheck the configuration, including the rules, and restart Prometheus:
podman exec prometheus promtool check config /etc/prometheus/prometheus.ymlpodman restart prometheusUnder Alerts in Prometheus, you’ll see both rules. Refresh the home page more than ten times, and HomePageBusy becomes Pending, and after a minute, Firing: