If an application or website starts running slower than usual or becomes unavailable, users complain about errors, and the business suffers losses. The cause of the failure is often difficult to detect, and while the search is underway, the service is idle.

Well-configured monitoring helps to prevent the occurrence of such problems and significantly reduce the time needed to fix them. This is where Prometheus and Grafana, popular monitoring tools, come to the rescue.

What is Prometheus?

Prometheus is a monitoring system. It collects metrics — data about the state of the server and its services, such as CPU usage, RAM usage, number of requests to the site, response time, and many others. The service stores the data in the database, which allows you to analyze the dynamics of the system status.

In order for monitoring to collect metrics, they must be presented in a format that is understandable to them. However, usually the target application or service does not have the built-in functionality to provide its metrics in the Prometheus format. To collect them and convert them into a compatible format, we use exporters, special adapter applications. The PromQL query language is used to analyze and extract this data.

There are a large number of ready-made exporters designed to collect metrics from a specific source, such as an operating system, database, or web server. An extensive catalog of ready-made exporters is presented here. For proprietary systems for which there is no ready-made exporter, developers write their own exporters that implement obtaining and converting the necessary metrics.

What is Grafana?

Grafana is a data visualization platform. It connects to Prometheus and displays metric data on dashboards in the form of graphs, charts, tables, and other visual elements.

In Grafana, you can create your own dashboards by combining information about different system components on one screen: CPU and memory usage, disk status, number of requests, response time, number of errors, and other indicators. Dashboards can be flexibly customized for specific tasks. The platform also supports the connection of various data sources, so it can be used not only with Prometheus, but also with other monitoring systems, databases and various services that provide data for analysis.

Grafana can also create and send incident notifications. However, we recommend using a separate component, Alertmanager, for this purpose: it provides extensive routing, grouping, and suppression of duplicate messages.

So, the Prometheus and Grafana bundle is built according to a fairly simple scheme.:

  1. The exporters collect metrics from servers and services.
  2. Prometheus polls exporters at regular intervals.
  3. The metrics are stored in the Prometheus internal storage.
  4. Grafana connects to Prometheus and displays data on dashboards.
  5. Alertmanager sends notifications when problems occur.

Installing Prometheus

Consider installing on an Ubuntu Server. The instructions are also suitable for other Linux distributions — the differences are only in the package manager (for example, yum or dnf instead of apt). The commands in the article are supposed to be executed with superuser rights (sudo).

Create a user:

sudo useradd -r -M -s /usr/sbin/nologin prometheus

Download the current version of Prometheus from the official website or from the official repository on Github. Unpack it:

cd /tmp
wget https://github.com/prometheus/prometheus/releases/download/v3.12.0/prometheus-3.12.0.linux-amd64.tar.gz
tar xzvf prometheus-*.tar.gz

Create directories, copy the executable files, and assign an owner.:

sudo mkdir /etc/prometheus
sudo mkdir /var/lib/prometheus
sudo mv prometheus-*/prometheus /usr/local/bin/
sudo mv prometheus-*/promtool /usr/local/bin/
sudo chown root:root /usr/local/bin/prometheus
sudo chown root:root /usr/local/bin/promtool
sudo chown -R prometheus:prometheus /var/lib/prometheus
sudo chown -R prometheus:prometheus /etc/prometheus

Create a Prometheus configuration file:

sudo nano /etc/prometheus/prometheus.yml

Insert:

global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: prometheus

    static_configs:
      - targets:
        - localhost:9090

Check the Prometheus configuration:

promtool check config /etc/prometheus/prometheus.yml

If everything is in order, the check will output SUCCESS. If not, the file structure may have gone astray — each level of the yml file structure should be shifted by 2 spaces.

Create a service unit file in systemd:

sudo nano /etc/systemd/system/prometheus.service

Insert:

[Unit]
Description=Prometheus Monitoring
Wants=network-online.target
After=network-online.target

[Service]
User=prometheus
Group=prometheus
Type=simple

ExecStart=/usr/local/bin/prometheus \
  --config.file=/etc/prometheus/prometheus.yml \
  --storage.tsdb.path=/var/lib/prometheus

Restart=always

[Install]
WantedBy=multi-user.target

Turn on the service and check its operation:

sudo systemctl daemon-reload
sudo systemctl enable --now prometheus
sudo systemctl status prometheus.service

Prometheus will start on port 9090.

Then check the availability of Prometheus in the browser.:

http://server-ip:9090

The Prometheus web interface opens, which allows you to run PromQL queries, view graphs, monitor the status of monitoring targets, and check the rules and alerts. The interface is convenient for configuring and diagnosing the monitoring system, but Grafana is usually used to constantly monitor the state of the infrastructure and create informative dashboards. It has become the standard solution for data visualization at Prometheus.

The main sections of the Prometheus interface:

Expression is the main section designed to perform queries to the database of metrics using the PromQL language.

  • Alerts — displays a list of all alert rules and their current status.
  • Status — contains official information about Prometheus operation.
  • Targets — a list of all monitoring targets, their status, the time of the last survey, and possible errors.
  • Configuration — the current Prometheus configuration.
  • Rules — a list of Recording Rules and Alert Rules.

To get metrics about the server’s status (CPU usage, RAM usage, disk space, etc.), you need to connect the exporter. The standard solution for these tasks is Node Exporter.

Installing Node Exporter

You can download the current version of Node Exporter from the official Prometheus website or from the official repository on Github.

Create a node_exporter user:

sudo useradd -r -M -s /usr/sbin/nologin node_exporter

Download the archive and unzip it:

cd /tmp
wget https://github.com/prometheus/node_exporter/releases/download/v1.11.1/node_exporter-1.11.1.linux-amd64.tar.gz
tar xzvf node_exporter*.tar.gz

Copy the executable file and assign the owner:

sudo mv node_exporter-*/node_exporter /usr/local/bin/
sudo chown root:root /usr/local/bin/node_exporter

Connect node_exporter to Prometheus. Open the Prometheus configuration file:

sudo nano /etc/prometheus/prometheus.yml

Add:

- job_name: node

  scrape_interval: 5s  

  static_configs:
    - targets: ['localhost:9100']

As part of this article, Node Exporter is installed on the same server where Prometheus is running. However, in real operation, Node Exporter is usually installed on every server that needs to be monitored. In this case, the Prometheus configuration must specify the server’s IP address instead of localhost.

Create a service unit file in systemd:

sudo nano /etc/systemd/system/node_exporter.service

Insert:

[Unit]
Description=Prometheus Node Exporter
After=network.target

[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter

[Install]
WantedBy=multi-user.target

Turn on the node_exporter service and check its operation:

sudo systemctl daemon-reload
sudo systemctl enable --now node_exporter
sudo systemctl status node_exporter

Check the Prometheus configuration:

promtool check config /etc/prometheus/prometheus.yml

If the check is successful, restart the Prometheus service.:

sudo systemctl restart prometheus

The service will start on port 9100.

Open the node_exporter metrics page in your browser:

http://server-ip:9100/metrics

The structure of Prometheus metrics

On the page http://server-ip:9100/metrics you will see all the metrics that Node Exporter collects.

Each metric is accompanied by service information: # HELP — contains a brief description of the purpose of the metric, # TYPE — indicates the type of metric (counter, gauge, histogram or summary), then the current metric value is displayed.

For example:

# HELP node_cpu_seconds_total Seconds the CPUs spent in each mode.
# TYPE node_cpu_seconds_total counter
node_cpu_seconds_total{cpu="0",mode="idle"} 62431.48

In this example:

  • node_cpu_seconds_total is the name of the metric.;
  • “cpu”=”0” and “mode”=”idle” are labels that specify which logical processor (core) and operating mode (idle — idle processor) the metric value is given for.;
  • 62431.48 is the current metric value.

The metric shows that logical processor #0 has been idle for a total of 62431.48 seconds since the system was started.

Monitoring objectives and basic concepts

One of the most useful sections in the Prometheus web interface is Target health. In it, you can check the status of all configured targets from which Prometheus is trying to collect metrics.

To go to the section, open Prometheus → Status → Target health.

Here it is necessary to expand the terms a little:

  • Job (monitoring task) is a logical group of monitoring goals (targets) united by common parameters for collecting metrics. Each job has a corresponding job_name parameter.
  • A target is a monitoring object that provides metrics over HTTP. The target is, for example, an exporter, an application that provides metrics itself, or even Prometheus itself. When you connect a new object in the Prometheus configuration, the corresponding target appears in its interface.
  • Target health — the health status of the goals.
  • Scrape (metrics collection) is a process in which Prometheus sends an HTTP request to the endpoint of a monitoring target, receives metrics and stores them in its database.
  • Scrap interval — the frequency with which Prometheus collects metrics.
  • Instance is a label that allows you to distinguish one monitoring target from another. It contains the host:port address by default, but it can be overridden. It is used for filtering and selecting metrics when building queries.

In the screenshot, we see two monitoring targets grouped by monitoring tasks (jobs) — node and prometheus.

  • node — collecting metrics from Node Exporter (http://localhost:9100/metrics ).
  • prometheus — collection of proprietary Prometheus metrics (http://localhost:9090/metrics ). It is used to monitor the Prometheus server itself.

Both monitoring targets are operational (UP).

Installing and configuring Grafana

You can get a link to the deb package of the current version of Grafana on the official website.

sudo apt-get install -y adduser libfontconfig1 musl
wget https://dl.grafana.com/grafana-enterprise/release/13.1.0/grafana-enterprise_13.1.0_28013217238_linux_amd64.deb
sudo dpkg -i grafana-enterprise_13.1.0_28013217238_linux_amd64.deb

The Grafana web interface is available at the URL:

http://server-ip:3000

Credentials: login — admin, password — admin.

After the first login, Grafana will ask you to change your password.

Now let’s connect Prometheus to Grafana.

Go to Connections → Data Sources and click Add datasource.

Choose Prometheus.

In the Connection field, enter http://localhost:9090 and click Save & test at the bottom of the page.

A successful connection message should be displayed.:

Grafana can now use metrics collected by Prometheus.

The main element of the Grafana interface is Dashboards, which are dashboards with a visual representation of metrics. You can use ready-made dashboards or create your own. The official Grafana website has a section with thousands of ready-made dashboards.

Let’s set up the popular Node Exporter Full dashboard, which provides a graphical representation of almost all metrics collected by Node exporter.

Go to Dashboards and select New → Import dashboard.

Enter the dashboard ID — 1860.

A panel with graphs of the main server parameters will load.

Setting up alerts

To receive notifications when the server is unavailable, the server load is high, or the free disk space is running out, you need to configure Alertmanager. It supports sending alerts to many external systems.:

  • Email;
  • telegram;
  • Slack;
  • Discord and others.

Alertmanager can also send requests via webhooks to any systems that can accept HTTP requests.

Installing Alertmanager

You can download the current version of Alertmanager from the official Prometheus website or from the GitHub repository.

Create an alertmanager user:

sudo useradd -r -M -s /usr/sbin/nologin alertmanager

Download the archive and unzip it:

cd /tmp
wget https://github.com/prometheus/alertmanager/releases/download/v0.33.0/alertmanager-0.33.0.linux-amd64.tar.gz
tar xvfz alertmanager-0.33.0.linux-amd64.tar.gz

Copy the executable file and assign the owner:

cd alertmanager-*.linux-amd64

sudo cp alertmanager /usr/local/bin/
sudo cp amtool /usr/local/bin/

sudo mkdir -p /etc/alertmanager
sudo mkdir -p /var/lib/alertmanager

sudo chown -R alertmanager:alertmanager /etc/alertmanager
sudo chown -R alertmanager:alertmanager /var/lib/alertmanager

Now, as an example, let’s set up sending alerts by email.

Create the Alertmanager configuration file:

sudo nano /etc/alertmanager/alertmanager.yml

global:
  smtp_smarthost: 'smtp.gmail.com:587'
  smtp_from: 'monitor@example.com'
  smtp_auth_username: 'monitor@example.com'
  smtp_auth_password: 'APP_PASSWORD'

route:
  receiver: email
  group_wait: 10s
  group_interval: 30s
  repeat_interval: 1m

receivers:
  - name: email
    email_configs:
      - to: 'admin@example.com'
        send_resolved: true

Here:

  • group_wait — the time period before the first shipment.
  • group_interval — the frequency of sending new alerts in the group.
  • repeat_interval — the frequency of active alerts being repeated.

Check the Alertmanager configuration:

amtool check-config /etc/alertmanager/alertmanager.yml

Create a service unit file in systemd:

sudo nano /etc/systemd/system/alertmanager.service

Insert:

[Unit]
Description=Prometheus Alertmanager
After=network.target

[Service]
User=alertmanager
Group=alertmanager

ExecStart=/usr/local/bin/alertmanager \
  --config.file=/etc/alertmanager/alertmanager.yml \
  --storage.path=/var/lib/alertmanager \
  --cluster.listen-address=""

Restart=always

[Install]
WantedBy=multi-user.target

sudo systemctl daemon-reload
sudo systemctl enable --now alertmanager
sudo systemctl status alertmanager

You can check the operation of the Alertmanager by downloading the page:

http://server-ip:9093/#/alerts

Now connect the Alertmanager to Prometheus:

nano /etc/prometheus/prometheus.yml

Add:

alerting:
alertmanagers:
  - static_configs:
      - targets:
        - localhost:9093

rule_files:
  - alerts.yml

Create a rule file:

nano /etc/prometheus/alerts.yml

Add a simple alert that will work if the server is unavailable.:

groups:

- name: nodes

  rules:
  - alert: NodeDown
    expr: up{job="node"} == 0
    for: 2m

    labels:
      severity: critical

    annotations:
      summary: "The server is unavailable"
      description: "Хост {{ $labels.instance }} unavailable for more than 2 minutes!"

Check the syntax:

promtool check rules /etc/prometheus/alerts.yml

Restart Prometheus:

systemctl restart prometheus

On the page https://server-ip:9090/alerts You can see the list of alerts and their status.

Monitoring of key server and website metrics

Now let’s set up alerts for critical metrics.:

  • CPU usage;
  • RAM usage;
  • I/O of the disk subsystem;
  • free disk space.

Add the rules to the /etc/prometheus/alerts.yml file:

- alert: CPU

    expr: node_load1 > on(instance)(count by(instance) (node_cpu_seconds_total{mode="idle"}))
    for: 1m

    labels:
      severity: critical

    annotations:
      summary: "High Load Average"
      description: "Load average on the server {{ $labels.instance }} compose {{ printf \"%.2f\" $value }} more than 1 minute!"

  - alert: RAM

    expr: ((1 - (node_memory_MemAvailable_bytes{job="node"} / node_memory_MemTotal_bytes{job="node"})) * 100)>90
    for: 1m

    labels:
      severity: critical

    annotations:
      summary: "RAM load"
      description: "The server is running {{ $labels.instance }} out {{ printf \"%.2f\" $value }}% RAM!"

  - alert: DiskCriticalUtilization

    expr: rate(node_disk_io_time_seconds_total[1m]) > 0.9
    for: 1m

    labels:
      severity: critical

    annotations:
      summary: "Critical disk loading"
      description: "Disk utilization {{ $labels.device }} more than 90%!"

  - alert: DiskAvailableSpace

    expr: node_filesystem_avail_bytes{mountpoint="/"}/1024/1024/1024 < 10
    for: 1m

    labels:
      severity: critical

    annotations:
      summary: "The free space is running out"
      description: "On disk {{ $labels.device }} free {{ printf \"%.2f\" $value }} GB!"

Check the syntax:

promtool check rules /etc/prometheus/alerts.yml

Restart Prometheus:

systemctl restart prometheus

Site accessibility control

Blackbox exporter, an exporter for Prometheus that can check the availability of a web resource, will help with monitoring the availability of a web resource.:

  • HTTP/HTTPS (sites, API);
  • SSL/TLS certificates (Validity period, validity);
  • ICMP (ping);
  • TCP-ports;
  • DNS.

In addition, Blackbox exporter can collect, for example, such metrics:

  • probe_success — site availability;
  • probe_http_status_code — HTTP response code (200, 301, 404, 500, etc.);
  • probe_duration_seconds – verification time;
  • probe_ssl_earliest_cert_expiry — expiration date of the SSL certificate;
  • probe_http_redirects — number of redirects;
  • probe_tls_version_info is the TLS version used.

You can download Blackbox exporter from here.

Let’s install Blackbox exporter by analogy with Node exporter:

sudo useradd --no-create-home --shell /usr/sbin/nologin blackbox

cd /tmp

wget https://github.com/prometheus/blackbox_exporter/releases/download/v0.28.0/blackbox_exporter-0.28.0.linux-amd64.tar.gz

tar xzvf blackbox_exporter*

sudo mkdir -p /etc/blackbox

sudo cp blackbox_exporter*/blackbox_exporter  /usr/local/bin/

sudo chown root:root /usr/local/bin/blackbox_exporter

sudo nano /etc/blackbox/blackbox.yml

modules:
  http_2xx:
    prober: http
    timeout: 5s
    http:
      preferred_ip_protocol: ip4
      valid_status_codes: []
      
nano /etc/systemd/system/blackbox_exporter.service

[Unit]
Description=Prometheus Blackbox Exporter

After=network.target

[Service]
User=blackbox
Group=blackbox
ExecStart=/usr/local/bin/blackbox_exporter \
  --config.file=/etc/blackbox/blackbox.yml

Restart=always

[Install]
WantedBy=multi-user.target


sudo systemctl daemon-reload
sudo systemctl enable --now blackbox_exporter
sudo systemctl status blackbox_exporter

Create a file with a list of sites to check:

sudo mkdir -p /etc/prometheus/targets

sudo nano /etc/prometheus/targets/blackbox.yml

- targets:
    - https://google.com
    - https://ya.ru
    - https://example.com

Add a new task to Prometheus:

sudo nano /etc/prometheus/prometheus.yml

- job_name: blackbox-http
    metrics_path: /probe

    params:
      module:
        - http_2xx

    file_sd_configs:
      - files:
          - /etc/prometheus/targets/blackbox.yml

    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target

      - source_labels: [__param_target]
        target_label: instance

      - target_label: __address__
        replacement: localhost:9115

Check the configuration and restart the service.:

promtool check config /etc/prometheus/prometheus.yml

sudo systemctl restart prometheus

Blackbox Exporter will start on port 9115.

Blackbox doesn’t know anything about the /etc/prometheus/targets/blackbox.yml file. It just waits for requests of the form:

/probe?target=https://example.com&module=http_2xx.When Prometheus polls the Blackbox, it takes targets from the blackbox.yml and substitutes them in the target parameter. Page http://server-ip:9115 / shows only the results of manual queries and debug information.

To view the metrics of a specific site, open in a browser:

http://server-ip:9115/probe?target=https://example.com&module=http_2xx

To find out if Prometheus has started monitoring your sites, open Prometheus → Status → Target health. You will see tasks like blackbox-http with goals (sites) for verification.:

Setting up alerts:

  • site availability;
  • the validity of the SSL certificate.

Adding a new alert group to /etc/prometheus/alerts.yml:

- name: website

  rules:

  - alert: WebsiteDown

    expr: probe_success == 0
    for: 30s

    labels:
      severity: critical

    annotations:
      summary: "The site is unavailable"
      description: "{{ $labels.instance }} doesn't respond"

  - alert: SSLCertificateExpire

    expr: (probe_ssl_earliest_cert_expiry - time()) / 86400 < 14
    for: 10m

    labels:
      severity: critical

    annotations:
      summary: "The certificate is about to expire"
      description: "The validity period of the domain certificate {{ $labels.instance }} expires after {{ printf \"%.0f\" $value }} days."

An alert will be sent if the site is unavailable for 30 seconds and/or the SSL certificate expires in less than 14 days.

Creating a dashboard in Grafana for site monitoring

It is convenient to have a separate dashboard for site monitoring. You can use a ready-made solution, but it is more convenient to customize the dashboard for your tasks.
Let’s look at an example of creating a dashboard for monitoring a website. Go to the Dashboards section and select New dashboard:

Click on the plus sign on the right to add a panel to our dashboard.:

In the new panel, click Configure visualization. The settings section of the current panel opens.

Preview area (1) — displays the result of query execution. After selecting the visualization type, a graph, table, or other dashboard element will be displayed here.

Query editor (2) is designed for creating and configuring queries to a data source (for example, Prometheus). Here, metrics are selected, filters, functions, and data display conditions are set.

Visualization selection (3) — allows you to select a way to display the received data. There are various types of charts and graphs available — Time series, Stat, Gauge, Bar gauge, Table, Pie chart and others.

Let’s set up the website accessibility indicator panel.

In the Query editor constructor, select the following options and click Run queries:

On the right, in the visualization selection area, select view — Stat.

Enter the name of the panel — Title.

Panel styles:

Set the Value mappings (in the Color column, set the color when the site is available/unavailable):

Go back to the dashboard. Let’s add a few more panels.

A dashboard for monitoring website availability over time (timeline).

The request is the same.

Visualisation - State timeline

Title - Timeline
Show values - Never
Axis:
Width - 0
Value mappings - как в панели выше
Color scheme - Green-Yellow-Red

The panel shows the server response time schedule.

Queries:

Metric - probe_duration_seconds
Label filters:
instance = https://testtest.fvds.ru (ваш сайт)

All visualisations - Time series
Title - Время ответа
Legend:
Visibility - Off

The other settings are by default.

Panel — the number of days until the expiration date of the SSL certificate.

Queries:

Title - SSL certificate
Panel styles - Background color from thresholds, no sparkline

Standart options:
Decimals - 0
Color scheme - From thresholds (by value)

Thresholds:

14 is the threshold in days below which the panel will turn red.

Don’t forget to save the dashboard by clicking the Save button. On the dashboard page, you can change the size and position of the panels. As a result, we will get such a dashboard:

Best practices

  • You should not collect hundreds of metrics without understanding their value — choose only critical metrics. Overloaded dashboards make monitoring more difficult: they make it harder to notice really important changes and respond promptly to a problem.
  • Divide dashboards according to their purpose. Create separate panels for different tasks: infrastructure, databases, web services, containers. One huge dashboard quickly becomes useless — it’s difficult to navigate it.
  • Set up alerts wisely. If there are too many notifications and not all of them are important, the administrator will ignore them. Set up alerts only for critical events.
  • Store metrics wisely. Prometheus is not designed for long-term data storage. Other systems are used for this task (for example, Thanos or VictoriaMetrics).