問題現象
通過benchmarksql對MySQL數據庫做壓測完發現Grafana關于該數據庫的監控圖趨勢不連續,監控數據異常。
說明:Prometheus+mysql+expoter都通過容器運行
日志分析
檢查了其他數據庫節點跟主機節點趨勢圖均正常,排除 Prometheus 的問題,檢查 expoter 日志發現有報錯信息:
time=2025-06-12T06:18:52.960Z level=ERROR source=exporter.go:131 msg="Error opening connection to database" err="Error 1203 (42000): User root already has more than 'max_user_connections' active connections"
通過日志代碼 1203 定位分析 MySQL 的用戶 root
當前已經達到了最大連接數限制(max_user_connections
),導致 mysqld_exporter
無法再建立新的連接來采集監控數據。
-
查看活躍連接數
?
MySQL [test1]> SHOW GLOBAL STATUS LIKE 'Threads_connected';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 1900 |
+-------------------+-------+
1 row in set (0.01 sec)
-
查看 MySQL 中
root
用戶的最大連接數限制(MAX_USER_CONNECTIONS
):
MySQL [test1]> SELECT -> USER, -> HOST, -> MAX_USER_CONNECTIONS -> FROM -> mysql.user -> WHERE -> USER = 'root'; +------+-----------+----------------------+ | USER | HOST ?????| MAX_USER_CONNECTIONS | +------+-----------+----------------------+ | root | % ????????| ???????????????????0 | | root | localhost | ???????????????????0 | +------+-----------+----------------------+ 2 rows in set (0.00 sec)
-
MAX_USER_CONNECTIONS = 0
表示該用戶使用的是 全局最大連接限制,而不是單獨設置的值。 -
所以
root@%
和root@
localhost
都會受到系統變量max_user_connections
的限制。
-
查看連接數設置
MySQL [test1]> show variables like '%connection%'; +-----------------------------------+----------------------+ | Variable_name ????????????????????| Value ???????????????| +-----------------------------------+----------------------+ | character_set_connection ???????? | utf8mb3 ?????????????| | collation_connection????????????? | utf8_general_ci ?????| | connection_memory_chunk_size ?????| 8912 ????????????????| | connection_memory_limit ???????? | 18446744073709551615 | | global_connection_memory_limit | 18446744073709551615 | | global_connection_memory_tracking | OFF ?????????????????| | max_connections ???????????????? | 10000 ???????????????| | max_user_connections ???????? | 1900 ????????????????| | mysqlx_max_connections ???????? | 100 ??????????????? ?| +-----------------------------------+----------------------+
參數名 | 值 | 含義 |
max_connections | 10000 | MySQL 允許的最大連接數(包括所有用戶) |
max_user_connections | 1900 | 單個用戶允許的最大連接數(root 用戶受此限制) |
問題定位
-
root
用戶沒有設置獨立的MAX_USER_CONNECTIONS
,所以受限于全局變量max_user_connections = 1900
-
MySQL 整體最多支持
max_connections = 10000
個連接 -
因此,一個用戶最多只能建立 1900 個連接,超過這個數字就會報錯
Error 1203: User root already has more than 'max_user_connections' active connections
解決辦法
方案一:更換 mysqld_exporter
使用的數據庫用戶(推薦)
CREATE USER 'exporter'@'%' IDENTIFIED BY 'your_password';
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'%';
FLUSH PRIVILEGES;
然后修改 mysqld_exporter 的配置文件 my.cnf 或啟動參數,使用新用戶連接:
[client] user=exporter password=your_password host=localhost port=3306
方案二:增加 root
用戶的最大連接數限制
ALTER USER 'root'@'%' WITH MAX_USER_CONNECTIONS 10000; FLUSH PRIVILEGES;
復測
確認趨勢圖正常