> 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-postgres.md).

# Мониторинг Postgres

## Ссылки

prometheus-community / postgres\_exporter: [github.com](https://github.com/prometheus-community/postgres_exporter/)

Как мониторить сотни инстансов PostgreSQL и не сойти с ума: [habr.com](https://habr.com/ru/companies/tantor/articles/940752/)

Шпаргалка по установке и настройке различных Prometheus exporter на Linux: [www.dmosk.ru](https://www.dmosk.ru/miniinstruktions.php?mini=exporter-prometheus)

## Установка Postgres exporter

Описано [тут](/utm-docs/dokumentaciya/utm-it/resheniya/subd/postgres/instansy/utm-postgres18-na-utm-db4-9.md#zapusk-docker-konteinera-s-postgres-exporter)

#### ​Альтернативный вариант установки Postgres exporter

<details>

<summary>(НЕ ЗАРАБОТАЛО!!!) Установка Postgres exporter в виде службы</summary>

На Linux сервере с Postgres выполнить:

```bash
# Создаем временную папку
mkdir ~/tmp
# Переходим во временную папку
cd ~/tmp
# Клонируем проект экспортера с гитхаба
git clone https://github.com/prometheus-community/postgres_exporter.git
# Переходим в загруженный каталог
cd postgres_exporter
# Собираем файлы пакета из исходников:
make build
```

Если мы получили ошибку:

```bash
sudo apt install make

# Устанавливаем переменную окружения с нужной версией GO
GO_VER=1.24.1
# Скачиваем исходник
curl -sLO https://go.dev/dl/go${GO_VER}.linux-amd64.tar.gz
# Устанавливаем GO
sudo tar -xzf go*.linux-amd64.tar.gz -C /usr/local && rm -f go*.linux-amd64.tar.gz
# Теперь можно выполнить сборку еще раз:
PATH=/usr/local/go/bin:$PATH make build
```

Полученный бинарник **postgres\_exporter** переносим в каталог **bin**:

```bash
sudo mv postgres_exporter /usr/local/bin/postgres_exporter
```

Почистить папки

```bash
cd ~/tmp
rm -rf postgres_exporter
```

Настроить сервис. Создать файл `/etc/systemd/system/postgres_exporter.service`

```bash
sudo nano /etc/systemd/system/postgres_exporter.service
```

Содержание файла `/etc/systemd/system/postgres_exporter.service`

```apache
[Unit]
Description=Prometheus PostgreSQL Exporter
Wants=network-online.target
After=network-online.target

[Service]
User=postgres
Group=postgres
Type=simple
ExecStart=/usr/local/bin/postgres_exporter \
  --web.listen-address=0.0.0.0:9187 \
  --web.telemetry-path=/metrics \
  --log.level=info \
  --extend.query-path=/etc/postgres_exporter/queries.yaml \
  DATA_SOURCE_NAME="postgresql://postgres_exporter:exporter_password@localhost:5432/postgres?sslmode=disable"

ExecReload=/bin/kill -HUP $MAINPID
Restart=always

[Install]
WantedBy=multi-user.target
```

Создаем учетную запись postgres:

```bash
# Создаем пользователя nodeusr:
sudo useradd --no-create-home --shell /bin/false postgres
# Задаем владельца для исполняемого файла:
sudo chown -R postgres:postgres /usr/local/bin/postgres_exporter
```

Включаем:

```bash
# Разрешаем автозапуск:
sudo systemctl enable postgres_exporter
# Запускаем службу:
sudo systemctl start postgres_exporter

# Статус
sudo systemctl status postgres_exporter

# Или если нужно перезапустить
sudo systemctl daemon-reload
sudo systemctl restart postgres_exporter
```

Можно проверить статус службы и прослушивание порта 9113:

```bash
systemctl status nginx_exporter
ss -tunlp | grep :9113
```

Также можно получить набор метрик:

```bash
curl 127.0.0.1:9113/metrics
```

</details>

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

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

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

<details>

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

Добавить ip сервера в секцию&#x20;

prometheus\prometheusSpec\additionalScrapeConfigs

```yaml
    additionalScrapeConfigs: |
      - job_name: 'postgres'
        scrape_interval: 5s
        static_configs:
          - targets:
            - 192.168.4.9:9187
            - <ip>:9100
```

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

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

</details>

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

{% hint style="info" %}
**ПРОРАБОТАТЬ!!!**
{% endhint %}

## Настройка 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:
    - name: 'postgres'
      orgId: 1
      folder: 'Postgres'
      type: file
      disableDeletion: false
      editable: true
      options:
        path: /var/lib/grafana/dashboards/postgres
        foldersFromFilesStructure: false

dashboards:
  postgres:
    455-postgres-overview:
      gnetId: 455
      revision: 2
      datasource: Prometheus
    9628-postgresql-database:
      gnetId: 9628
      revision: 8
      datasource: Prometheus
```

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

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

</details>

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

<details>

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

#### Postgres Overview&#x20;

Ссылка: [grafana.com](https://grafana.com/grafana/dashboards/455-postgres-overview/)\
ID: 455

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

#### PostgreSQL Database

Ссылка: [grafana.com](https://grafana.com/grafana/dashboards/9628-postgresql-database/)\
ID: 9628

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

</details>

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

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

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

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

<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-postgres.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.
