【Prometheus+Grafana系列】監控MySQL服務

前言

前面的一篇文章已經介紹了 docker-compose 搭建 Prometheus + Grafana 服務。當時實現了監控伺服器指標數據,是通過 node_exporter。Prometheus 還可用來監控很多服務,比如常見的 MySQL。本文就介紹如何通過 mysqld_exporter 來監控 MySQL 指標。

下載安裝包

cd /opt
wget //github.com/prometheus/mysqld_exporter/releases/download/v0.14.0/mysqld_exporter-0.14.0.linux-amd64.tar.gz
tar xvf mysqld_exporter-0.14.0.linux-amd64.tar.gz
mv mysqld_exporter-0.14.0.linux-amd64 mysqld_exporter
mv /opt/mysqld_exporter /usr/local/

創建監控帳號並授權

在需要監控的mysql上創建帳號並授權。

# 創建用戶
CREATE USER 'prometheus'@'%' IDENTIFIED BY 'prometheus';
# 分配許可權
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'prometheus'@'%';

添加資料庫監控帳號配置

vim /usr/local/mysqld_exporter/.my.cnf
添加如下內容

[client]
user=prometheus
password=prometheus
port=3306

啟動exporter客戶端

/usr/local/mysqld_exporter/mysqld_exporter --config.my-cnf=/usr/local/mysqld_exporter/.my.cnf

先手動啟動exporter看一下日誌,若有錯誤根據輸出調整即可。手動運行沒問題後,則進行下一步將其添加到系統服務中。

添加到系統服務

vim /etc/systemd/system/mysqld_exporter.service
添加如下內容

[Unit]
Description=mysqld_exporter
After=network.target
[Service]
ExecStart=/usr/local/mysqld_exporter/mysqld_exporter --config.my-cnf=/usr/local/mysqld_exporter/.my.cnf
Restart=on-failure
[Install]
WantedBy=multi-user.target

載入並重啟服務

# 載入配置
systemctl daemon-reload
# 啟動服務
systemctl restart mysqld_exporter.service
# 查看服務狀態
systemctl status mysqld_exporter.service
# 配置開機啟動
systemctl enable mysqld_exporter.service

查看收集數據

訪問exporter服務地址,查看數據收集情況。

curl //192.168.2.192:9104/metrics

修改 prometheus 配置文件,添加新節點

修改 prometheus 下的配置,prometheus.yml,添加如下內容。

scrape_configs:  
  # 添加job
  - job_name: 'mysql-192'
    static_configs:
     # 配置監控端,即上面我們啟動的 mysqld_exporter 服務
     - targets: ['192.168.2.192:9104']
       labels:
          instance: mysql

重啟 prometheus 服務

上一步修改了 prometheus.yml,需要重啟下 prometheus 服務。

cd /var/workspace/docker-prometheus
docker-compose stop prometheus
docker-compose up -d --build prometheus

查看 prometheus 中服務添加情況

查看 targets 是否添加成功
image.png

查看 mysql 監控資訊

mysql_global_status_aborted_clients

image.png

在 grafana 中添加 data sources

image.png

image.png

image.png
添加 prometheus 服務地址,此處由於服務是基於 docker-compose 構建的,沒有填寫ip,直接填寫服務名即可。

在 grafana 中導入 mysql 監控

image.png
輸入官方模版 id,7362,點擊 load。然後按照下圖選擇確認即可。
image.png

監控展示

上一步導入成功後,會自動跳轉到監控面板頁面,如下圖。默認的格式已經非常豐富可以直接使用了,也可以根據自己需求調整位置和配置。
image.png

Tags: