> For the complete documentation index, see [llms.txt](https://utm-1.gitbook.io/utm-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://utm-1.gitbook.io/utm-docs/dokumentaciya/utm-it/resheniya/monitoring/prometheus/monitoring-saitov.md).

# Мониторинг сайтов

## Ссылки

prometheus-blackbox-exporter: [artifacthub.io](https://artifacthub.io/packages/helm/prometheus-community/prometheus-blackbox-exporter?ref=blog.knell.it)

Prometheus Blackbox Exporter: [sir5kong.github.io](https://sir5kong.github.io/helm-charts-hub/prometheus-community/prometheus-blackbox-exporter/)

prometheus-community / helm-charts - Prometheus Blackbox Exporter: [github.com](https://github.com/prometheus-community/helm-charts/blob/main/charts/prometheus-blackbox-exporter/README.md)

Automating Blackbox Monitoring for your Helm Chart: [christianhuth.de](https://christianhuth.de/automating-blackbox-monitoring-for-your-helm-chart/)

Blackbox Exporter: [platformv.sbertech.ru2F](https://platformv.sbertech.ru/docs/public/K8S/3.1.0/common/documents/administration-guide/1-Blackbox-exporter.html?utm_referrer=https%3A%2F%2Falice.yandex.ru%2F)

Kubernetes: мониторинг c помощью Prometheus: [www.agima.ru](https://www.agima.ru/blog/development/kubernetes-monitoring-c-nbsp-pomoshchyu-prometheus/)

Мониторинг в K8s с помощью Prometheus: [selectel.ru](https://selectel.ru/blog/tutorials/monitoring-in-k8s-with-prometheus/)

Понимание и использование шаблона экспортера для нескольких целей: [prometheus.io](https://prometheus.io/docs/guides/multi-target-exporter/)

Prometheus: мониторинг HTTP через Blackbox экспортер: [habr.com](https://habr.com/ru/companies/otus/articles/500448/)

TaRaKaN41K / Monitoring\_Prometheus\_Blackbox-Exporter: [github.com](https://github.com/TaRaKaN41K/Monitoring_Prometheus_Blackbox-Exporter)

Система визуализации и мониторинга. Grafana + Prometheus: [habr.com](https://habr.com/ru/articles/757494/)

Как отслеживать производительность веб-сайта с помощью Blackbox Exporter и Grafana?: [geekflare.com](https://geekflare.com/dev/monitor-website-with-blackbox-prometheus-grafana/)

Как отслеживать производительность веб-сайта с помощью Blackbox Exporter и Grafana: подробное руководство: [mcngmarketing.com](https://mcngmarketing.com/resources/monitor-website-with-blackbox-prometheus-grafana)

Использование Prometheus Blackbox Exporter для мониторинга URL-адресов: [opsverse.io](https://opsverse.io/2023/02/24/using_prometheus_blackbox_exporter_to_monitor_grafana_endpoints/)

Prometheus-Grafana с использованием экспортера BlackBox: [dev.to](https://dev.to/kannanbaskaran/prometheus-grafana-using-blackbox-exporter-k83)

Blackbox‑мониторинг сайтов: проверки HTTP/TCP/ICMP и алерты в Prometheus: [fastfox.pro](https://fastfox.pro/blog/tutorials/prometheus-blackbox-http-tcp-icmp/)

## Инструкция от Яндекс Алисы

<details>

<summary>Инструкция</summary>

#### Запрос

Буду развертывать в Kubernetes через Argo CD на основе helm чарта. Также у меня в Kubernetes развернут Prometheus и отдельно Grafana. Нужна инструкция по развертыванию экспортера, а также настройке Prometheus и Grafana. У меня есть несколько сайтов за которыми нужно следить. А также есть несколько сервисов, доступных по https, за которыми тоже нужно следить:&#x20;

#### Ответ

Ниже — пошаговая инструкция по развёртыванию **Blackbox Exporter** в Kubernetes через **Argo CD** (на базе Helm‑чарта), настройке **Prometheus** для сбора метрик и **Grafana** для визуализации.

***

### 1. Развёртывание Blackbox Exporter через Argo CD

#### Шаг 1. Подготовьте Helm‑чарт и values

1. **Добавьте репозиторий Prometheus‑Community** (если ещё не добавлен):

   bash

   ```bash
   helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
   helm repo update
   ```
2. **Создайте `values.yaml`** для настройки чарта (пример ниже). Сохраните файл в репозитории, который мониторит Argo CD.

   **Пример `values.yaml`:**

   yaml

   ```yaml
   # values.yaml
   blackboxExporter:
     config:
       modules:
         http_2xx:
           prober: http
           timeout: 10s
           http:
             valid_status_codes: [200, 301, 302]
             method: GET
             no_follow_redirects: false
             fail_if_ssl: false
             fail_if_not_ssl: false
             tls_config:
               insecure_skip_verify: true  # если нужны самоподписанные сертификаты
         https_2xx:
           prober: http
           timeout: 10s
           http:
             valid_status_codes: [200]
             method: GET
             tls_config:
               insecure_skip_verify: false  # проверка сертификатов

     service:
       type: ClusterIP
       ports:
         http: 9115

   # Включение ServiceMonitor (для Prometheus)
   serviceMonitor:
     enabled: true
     namespace: monitoring  # укажите namespace Prometheus
     interval: 30s
     scrapeTimeout: 25s
     selector:
       matchLabels:
         app: blackbox-exporter
     endpoints:
       - port: http
         path: /probe
         params:
           module: [http_2xx]
   ```

   > **Примечание:**
   >
   > * `insecure_skip_verify: true` — если нужно игнорировать ошибки SSL (например, для тестовых доменов).
   > * Для продакшена лучше выставить `false` и настроить валидные сертификаты.

#### Шаг 2. Создайте Application в Argo CD

1. В интерфейсе Argo CD создайте новое приложение (`Application`).
2. Укажите:
   * **Repository**: ваш Git‑репозиторий с `values.yaml`.
   * **Path**: путь к директории с `values.yaml`.
   * **Destination**: namespace (например, `monitoring`).
   * **Chart**: `prometheus-community/prometheus-blackbox-exporter`.
   * **Values file**: `values.yaml`.
3. Примените конфигурацию. Argo CD развернёт:
   * Deployment Blackbox Exporter.
   * Service.
   * ServiceMonitor (если включён).

***

### 2. Настройка Prometheus

Если у вас уже установлен Prometheus (через Helm или иным способом), убедитесь, что:

1. **Prometheus Operator** активен (чтобы работал `ServiceMonitor`).
2. **ServiceMonitor** из чарта Blackbox Exporter автоматически добавлен в конфигурацию Prometheus (благодаря `serviceMonitor.enabled: true`).

#### Проверка

1. Проверьте, что `ServiceMonitor` создан:

   bash

   ```bash
   kubectl get servicemonitor -n monitoring
   ```

   Вы должны увидеть ресурс с меткой `app: blackbox-exporter`.
2. Убедитесь, что Prometheus видит цели:
   * Откройте веб‑интерфейс Prometheus → вкладка **Status** → **Targets**.
   * Найдите цели с меткой `job="blackbox-http"`. Они должны быть **UP**.

***

### 3. Настройка мониторинга конкретных сайтов

Чтобы Prometheus опрашивал ваши сайты, добавьте **job** в конфигурацию Prometheus.

#### Вариант 1. Через ConfigMap (если Prometheus не использует Operator)

1. Создайте ConfigMap с конфигурацией job:

   yaml

   ```yaml
   # prometheus-additional.yaml
   apiVersion: v1
   kind: ConfigMap
   metadata:
     name: prometheus-additional-scrape-configs
     namespace: monitoring
   data:
     additional-scrape-configs.yaml: |
       - job_name: 'blackbox-http'
         metrics_path: /probe
         params:
           module: [http_2xx]
         static_configs:
           - targets:
             - https://utmsoft.ru
             - https://test.utmsoft.ru
             - https://utmsoft.online
             - https://k8s-argocd.utmsoft.ru
             - https://k8s-grafana.utmsoft.ru
             - https://shootcatroid.utmsoft.ru/menu?action=ping
             - https://k8s-testapp.utmsoft.ru
         relabel_configs:
           - source_labels: [__address__]
             target_label: __param_target
           - source_labels: [__param_target]
             target_label: instance
           - target_label: __address__
             replacement: blackbox-exporter:9115  # адрес сервиса Blackbox Exporter
   ```
2. Примените ConfigMap:

   bash

   ```bash
   kubectl apply -f prometheus-additional.yaml
   ```
3. Перезапустите Prometheus (если требуется).

#### Вариант 2. Через Prometheus Operator (если используется)

Добавьте секцию `additionalScrapeConfigs` в `values.yaml` чарта Prometheus:

yaml

```yaml
prometheus:
  additionalScrapeConfigs:
    - job_name: 'blackbox-http'
      metrics_path: /probe
      params:
        module: [http_2xx]
      static_configs:
        - targets:
          - https://utmsoft.ru
          - https://test.utmsoft.ru
          - https://utmsoft.online
          - https://k8s-argocd.utmsoft.ru
          - https://k8s-grafana.utmsoft.ru
          - https://shootcatroid.utmsoft.ru/menu?action=ping
          - https://k8s-testapp.utmsoft.ru
      relabel_configs:
        - source_labels: [__address__]
          target_label: __param_target
        - source_labels: [__param_target]
          target_label: instance
        - target_label: __address__
          replacement: blackbox-exporter:9115
```

Затем обновите релиз Prometheus через Helm/Argo CD.

***

### 4. Настройка Grafana

#### Шаг 1. Добавьте источник данных Prometheus

1. В интерфейсе Grafana: **Configuration** → **Data Sources** → **Add data source**.
2. Выберите **Prometheus**.
3. Укажите URL Prometheus (например, `http://prometheus-server.monitoring.svc.cluster.local:9090`).
4. Сохраните.

#### Шаг 2. Импортируйте дашборд

1. Перейдите в **Dashboards** → **Import**.
2. Введите **ID дашборда**: `7587` (официальный дашборд Blackbox Exporter).
3. Выберите источник данных Prometheus.
4. Нажмите **Import**.

#### Шаг 3. Настройте оповещения (опционально)

В Grafana можно создать **Alerts** на основе метрик:

* `probe_success == 0` — сайт недоступен.
* `probe_duration_seconds > 2` — время ответа больше 2 сек.

Пример правила:

yaml

```yaml
- alert: WebsiteDown
  expr: probe_success{job="blackbox-http"} == 0
  for: 1m
  labels:
    severity: critical
  annotations:
    summary: "Сайт {{$labels.instance}} недоступен"
    description: "Сайт {{$labels.instance}} не отвечает более 1 минуты."
```

***

### Проверка работоспособности

1. **Проверьте цели в Prometheus** (вкладка **Targets**). Все сайты должны быть **UP**.
2. **Откройте дашборд в Grafana** — должны отображаться метрики по каждому сайту (статус, время ответа, SSL‑срок действия).
3. **Протестируйте оповещения** (можно временно отключить сайт для проверки).

***

### Итог

Вы настроили:

1. **Blackbox Exporter** в Kubernetes через Argo CD.
2. **Prometheus** для сбора метрик с ваших сайтов.
3. **Grafana** для визуализации и оповещений.

Если возникнут сложности — уточните, помогу отладить!

</details>

## Установка и настройка Blackbox Exporter через Argo CD

Установка описана [тут](/utm-docs/dokumentaciya/utm-it/resheniya/kubernetes/prilozheniya/monitoring/blackbox-exporter.md)

## Настройка Prometheus

### Регистрация target

Специально в Prometheus регистрировать targets не требуется.

Список наблюдаемых файлов настраивается в файле values.yaml в приложении [blackbox-exporter](https://app.gitbook.com/o/ydyc10nkiaS0aa9uq3Ai/s/UHLel8CyIki7deC8qpxM/~/edit/~/changes/310/instrukcii/dokumentaciya/kubernetes/prilozheniya/monitoring/blackbox-exporter#spisok-nablyudaemykh-saitov).

### Настройка правил оповещений

В файле `argocd\env-prod\apps\monitoring\prometheus\values.yaml`&#x20;

<details>

<summary>Изменения в файле <code>argocd\env-prod\apps\monitoring\prometheus\values.yaml</code></summary>

Изменить секцию additionalPrometheusRulesMap

```yaml
additionalPrometheusRulesMap:
  utm.alert.rules:
    groups:
    # Группа оповещений по сайтам
    - name: utm_alert_group_websites
      rules:
      # Оповещение, если сайт недоступен более 2 минут
      - alert: WebsiteDown
        expr: probe_success{job="blackbox-exporter-prometheus-blackbox-exporter"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Сайт {{ $labels.target }} недоступен"
          description: "Сайт {{ $labels.target }} не отвечает более 2 минут. Модуль: {{ $labels.module }}."

      # Оповещение при высоком времени отклика (например, >3 сек)
      - alert: HighResponseTime
        expr: probe_duration_seconds{job="blackbox-exporter-prometheus-blackbox-exporter"} > 3
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: "Высокое время отклика для {{ $labels.target }}"
          description: "Время отклика сайта {{ $labels.target }} превышает 3 секунды (текущее: {{ $value }} сек)."
```

Сделать коммит в репозиторий GitHub с обновлением файла `values.yaml`&#x20;

Дождаться, когда Argo CD обновить приложение k8s-prometheus.

</details>

## Настройка Grafana

### Импорт дашбордов из Argo CD

В файле `argocd\env-prod\apps\monitoring\grafana\values.yaml` добавить

<details>

<summary>Изменения в файле <code>argocd\env-prod\apps\monitoring\grafana\values.yaml</code></summary>

```yaml
dashboardProviders:
  dashboardproviders4.yaml:
    apiVersion: 1
    providers:
    - name: 'blackbox'
      orgId: 1
      folder: 'Blackbox'
      type: file
      disableDeletion: false
      editable: true
      options:
        path: /var/lib/grafana/dashboards/blackbox
        foldersFromFilesStructure: false

dashboards:
  redis: {}
```

Сделать коммит в репозиторий GitHub с обновлением файла `values.yaml`&#x20;

Дождаться, когда Argo CD обновить приложение k8s-grafana.

</details>

#### Дашборды

<details>

<summary>Описание импортируемых дашбордов</summary>

#### Prometheus Blackbox Exporter

Ссылка: [grafana.com](https://grafana.com/grafana/dashboards/7587-prometheus-blackbox-exporter/)

ID = 7587

<figure><img src="/files/ONE84vuZL3pfOqViZpzq" alt=""><figcaption></figcaption></figure>

#### Blackbox Exporter (HTTP prober)

Ссылка: [grafana.com](https://grafana.com/grafana/dashboards/13659-blackbox-exporter-http-prober/)

ID = 13659

<figure><img src="/files/ubrHsqMcK32BPWQ2veU1" alt=""><figcaption></figcaption></figure>

</details>

### Ручной импорт дашбордов

В Grafana: Dashboards → Import → вставь ID  → выбери источник Prometheus.

Каталог в дашбордах: `Blackbox`

#### Дашборды

<details>

<summary>Описание импортируемых дашбордов</summary>

Пока нет

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://utm-1.gitbook.io/utm-docs/dokumentaciya/utm-it/resheniya/monitoring/prometheus/monitoring-saitov.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
