Разделы документации

Оптимизация MySQL с MySQLTuner

MySQLTuner — скрипт на языке Perl, который помогает оптимизировать настройки MySQL или MariaDB для максимальной производительности в условиях доступных на сервере ресурсов.

Скрипт анализирует статистику работы сервера MySQL, оценивает текущую конфигурацию MySQL и сервера, а затем выдаёт список параметров, значения которых можно оптимизировать для оптимальной работы сервера MySQL.

Важно: Для правильного анализа необходимо, чтобы сервер MySQL проработал минимум одни сутки до момента запуска MySQLTuner. Это необходимо для сбора статистики, поскольку без неё анализ будет бесполезным.

Для установки MySQLTuner выполните следующие команды в SSH:

wget http://mysqltuner.pl/ -O mysqltuner.pl wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/basic_passwords.txt -O basic_passwords.txt wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/vulnerabilities.csv -O vulnerabilities.csv chmod +x mysqltuner.pl

Для запуска MySQLTuner выполните следующую команду в SSH:

perl mysqltuner.pl

Если скрипт укажет на необходимость ввода пароля пользователя root, то запустите скрипт следующим образом, указав пароль в команде:

perl mysqltuner.pl --user root --pass <ПАРОЛЬ>

Через некоторое время MySQLTuner выведет результат своей работы, который будет состоять из нескольких секций:

>> MySQLTuner 2.6.1 * Jean-Marie Renouard <jmrenouard@gmail.com> * Major Hayden <major@mhtx.net> >> Bug reports, feature requests, and downloads at http://mysqltuner.pl/ >> Run with '--help' for additional options and output filtering [--] Skipped version check for MySQLTuner script [--] Using mysql to check login [OK] Operating on 64-bit architecture -------- Storage Engine Statistics ----------------------------------------------------------------- [--] Status: +Aria +CSV +InnoDB +MEMORY +MRG_MyISAM +MyISAM +PERFORMANCE_SCHEMA +SEQUENCE [--] Data in Aria tables: 32.0K (Tables: 1) [--] Data in InnoDB tables: 8.8M (Tables: 66) [OK] Total fragmented tables: 0 [OK] Currently running supported MySQL version 10.6.19-MariaDB -------- Log file Recommendations ------------------------------------------------------------------ [!!] Log file doesn't exist -------- Analysis Performance Metrics -------------------------------------------------------------- [--] innodb_stats_on_metadata: OFF [OK] No stat updates during querying INFORMATION_SCHEMA. -------- Views Metrics ----------------------------------------------------------------------------- -------- Triggers Metrics -------------------------------------------------------------------------- -------- Routines Metrics -------------------------------------------------------------------------- -------- Security Recommendations ------------------------------------------------------------------ [OK] There are no anonymous accounts for any database users [OK] All database users have passwords assigned [--] There are 620 basic passwords in the list. -------- CVE Security Recommendations -------------------------------------------------------------- [OK] NO SECURITY CVE FOUND FOR YOUR VERSION -------- Performance Metrics ----------------------------------------------------------------------- [--] Up for: 18m 50s (2K q [1.815 qps], 50 conn, TX: 8M, RX: 362K) [--] Reads / Writes: 98% / 2% [--] Binary logging is disabled [--] Physical Memory : 950.5M [--] Max MySQL memory : 876.2M [--] Other process memory: 0B [--] Total buffers: 432.0M global + 2.9M per thread (151 max threads) [--] Performance_schema Max memory usage: 0B [--] Galera GCache Max memory usage: 0B [OK] Maximum reached memory usage: 440.8M (46.38% of installed RAM) [!!] Maximum possible memory usage: 876.2M (92.17% of installed RAM) [OK] Overall possible memory usage with other process is compatible with memory available [OK] Slow queries: 0% (0/2K) [OK] Highest usage of available connections: 1% (3/151) [OK] Aborted connections: 0.00% (0/50) [!!] Name resolution is active: a reverse name resolution is made for each new connection which can reduce performance [OK] Query cache is disabled by default due to mutex contention on multiprocessor machines. [OK] Sorts requiring temporary tables: 0% (0 temp sorts / 272 sorts) [OK] No joins without indexes [OK] Temporary tables created on disk: 10% (30 on disk / 284 total) [OK] Thread cache hit rate: 94% (3 created / 50 connections) [OK] Table cache hit rate: 87% (2K hits / 2K requests) [OK] table_definition_cache (400) is greater than number of tables (358) [OK] Open file limit used: 0% (59/32K) [OK] Table locks acquired immediately: 100% (73 immediate / 73 locks) -------- Performance schema ------------------------------------------------------------------------ [!!] Performance_schema should be activated. [--] Sys schema is installed. -------- ThreadPool Metrics ------------------------------------------------------------------------ [--] ThreadPool stat is disabled. -------- MyISAM Metrics ---------------------------------------------------------------------------- [--] General MyIsam metrics: [--] +-- Total MyISAM Tables : 0 [--] +-- Total MyISAM indexes : 0B [--] +-- KB Size :128.0M [--] +-- KB Used Size :23.3M [--] +-- KB used :18.2% [--] +-- Read KB hit rate: 0% (0 cached / 0 reads) [--] +-- Write KB hit rate: 0% (0 cached / 0 writes) [--] No MyISAM table(s) detected .... -------- InnoDB Metrics ---------------------------------------------------------------------------- [--] InnoDB is enabled. [OK] InnoDB File per table is activated [OK] InnoDB Buffer Pool size ( 128.0M ) under limit for 64 bits architecture: (17179869184.0G ) [OK] InnoDB buffer pool / data size: 128.0M / 8.8M [!!] Ratio InnoDB log file size / InnoDB Buffer pool size (75%): 96.0M * 1 / 128.0M should be equal to 25% [--] Number of InnoDB Buffer Pool Chunk: 1 for 1 Buffer Pool Instance(s) [OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances [OK] InnoDB Read buffer efficiency: 97.87% (37314 hits / 38128 total) [!!] InnoDB Write Log efficiency: 8.33% (4 hits / 48 total) [OK] InnoDB log waits: 0.00% (0 waits / 44 writes) -------- Aria Metrics ------------------------------------------------------------------------------ [--] Aria Storage Engine is enabled. [OK] Aria pagecache size / total Aria indexes: 128.0M/352.0K [!!] Aria pagecache hit rate: 90.9% (364 cached / 33 reads) -------- TokuDB Metrics ---------------------------------------------------------------------------- [--] TokuDB is disabled. -------- XtraDB Metrics ---------------------------------------------------------------------------- [--] XtraDB is disabled. -------- Galera Metrics ---------------------------------------------------------------------------- [--] Galera is disabled. -------- Replication Metrics ----------------------------------------------------------------------- [--] Galera Synchronous replication: NO [--] No replication slave(s) for this server. [--] Binlog format: MIXED [--] XA support enabled: ON [--] Semi synchronous replication Master: OFF [--] Semi synchronous replication Slave: OFF [--] This is a standalone server -------- Recommendations --------------------------------------------------------------------------- General recommendations: MySQL was started within the last 24 hours: recommendations may be inaccurate Reduce your overall MySQL memory footprint for system stability Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=ON Performance schema should be activated for better diagnostics Be careful, increasing innodb_log_file_size / innodb_log_files_in_group means higher crash recovery mean time Variables to adjust: *** MySQL's maximum memory usage is dangerously high *** *** Add RAM before increasing MySQL buffer variables *** skip-name-resolve=ON performance_schema=ON innodb_log_file_size should be (=32M) if possible, so InnoDB total log file size equals 25% of buffer pool size. innodb_log_buffer_size (> 16M)

Наше внимание должны привлечь те строки результата работы, которые отмечены знаком [!!], а также рекомендации по настройке в секциях General recommendations и Variables to adjust.

Получив рекомендации по настройке необходимо внести изменения в конфигурацию MySQL. Это можно сделать путём изменения файлов конфигурации.

В зависимости от ОС сервера файлы конфигурации могут храниться в разных папках:

  • В Debian и Ubuntu: /etc/mysql/my.cnf или /etc/mysql/mysql.conf.d/mysqld.cnf
  • В AlmaLinux и Rocky Linux: /etc/my.cnf или /etc/mysql/my.cnf

Определив файл конфигурации внесите рекомендованные настройки в секцию [mysqld]. Например, чтобы изменить параметр innodb_log_file_size из примера выше, внесите следующую настройку:

innodb_log_file_size=32M

После каждого изменения конфигурационного файла необходимо перезапустить MySQL.

Для Debian и Ubuntu:

systemctl restart mysql

Для AlmaLinux и Rocky Linux:

systemctl restart mysqld

Если на сервере установлена панель управления FASTPANEL, то изменить параметры MySQL можно через панель, используя меню УправлениеБазы данныхСерверы баз данных: