MySQL Tunerを使ってチューニングをしてみる。

はじめに

MySQLTunerなるものがあると聞いて、実際に使ってみる。

環境

Mac Sonoma 14.0
Docker Desktop 4.24.2 (124339)
MySQL 8.1.0

準備

今回、検証するにあたって、Docker を使用する。
下記のリポジトリに、データベースの勉強用リポジトリとして色々入れているので一緒に試せるようにした。
https://github.com/katsuobushiFPGA/db-study

db-tunerコンテナの作成

compose.ymlに下記を追加

  db-tuner:
    build: 
      context: ./db-tuner
      dockerfile: Dockerfile
    links:
      - db
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y mysql-client perl wget \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/*

WORKDIR /tmp

RUN 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

ENTRYPOINT [ "tail", "-f", "/dev/null" ]
docker compose up -d --build

でコンテナを作成する。

MySQLTunerを使う

docker compose exec db-tuner bash
# /tmpにいるので下記を実行する。  
perl mysqltuner.pl --host db  --user root --pass root

が基本 --user, --passでユーザーとパスワードを設定する。 設定しなくても聞かれるので、設定しない方が良い。(bash_historyにのったりするので)

# memory を16GBに設定したい場合
perl mysqltuner.pl --host db --forcemem 16000

出力はこんな感じ

root@6c0e91324465:/tmp# perl mysqltuner.pl --host db --forcemem 16000
 >>  MySQLTuner 2.3.2
         * 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
[!!] The --forceswap option is required for remote connections
[!!] Assuming Swap size is 1Gb for simplify remote connection usage
[--] Performing tests on db:3306
[--] Using mysql to check login
Please enter your MySQL administrative login: root
Please enter your MySQL administrative password: [--] Assuming 16000 MB of physical memory
[--] Assuming 1024 MB of swap space
[--] Skipping architecture check on remote host
[--] Using default 64 bits as target architecture
 
-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +ARCHIVE +BLACKHOLE +CSV -FEDERATED +InnoDB +MEMORY +MRG_MYISAM +MyISAM -ndbcluster -ndbinfo +PERFORMANCE_SCHEMA 
[--] Data in InnoDB tables: 160.0K (Tables: 7)
[OK] Total fragmented tables: 0
 
[OK] Currently running supported MySQL version 8.1.0
[--] Skipping system checks on remote host
[--] Skipping error log files checks on remote host
 
-------- Analysis Performance Metrics --------------------------------------------------------------
[--] innodb_stats_on_metadata: OFF
[OK] No stat updates during querying INFORMATION_SCHEMA.
 
-------- Views Metrics -----------------------------------------------------------------------------
 
-------- Triggers Metrics --------------------------------------------------------------------------
 
-------- Routines Metrics --------------------------------------------------------------------------
 
-------- Security Recommendations ------------------------------------------------------------------
[--] Skipped due to unsupported feature for MySQL 8.0+
 
-------- CVE Security Recommendations --------------------------------------------------------------
[OK] NO SECURITY CVE FOUND FOR YOUR VERSION
 
-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 11m 45s (195 q [0.277 qps], 75 conn, TX: 488K, RX: 23K)
[--] Reads / Writes: 100% / 0%
[--] Binary logging is enabled (GTID MODE: OFF)
[--] Physical Memory     : 15.6G
[--] Max MySQL memory    : 674.9M
[--] Other process memory: 0B
[--] Total buffers: 168.0M global + 1.9M per thread (151 max threads)
[--] Performance_schema Max memory usage: 219M
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 389.0M (2.43% of installed RAM)
[OK] Maximum possible memory usage: 674.9M (4.22% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (0/195)
[OK] Highest usage of available connections: 0% (1/151)
[OK] Aborted connections: 2.67% (2/75)
[--] Query cache has been removed since MySQL 8.0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 16 sorts)
[!!] Joins performed without indexes: 4
[OK] Temporary tables created on disk: 0% (0 on disk / 18 total)
[OK] Thread cache hit rate: 98% (1 created / 75 connections)
[OK] Table cache hit rate: 92% (6K hits / 6K requests)
[OK] table_definition_cache (2000) is greater than number of tables (335)
[OK] Open file limit used: 0% (6/1M)
[OK] Table locks acquired immediately: 100% (12 immediate / 12 locks)
[OK] Binlog cache memory access: 0% (0 Memory / 0 Total)
 
-------- Performance schema ------------------------------------------------------------------------
[--] Performance_schema is activated.
[--] Memory used by Performance_schema: 219.1M
[--] 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 :8.0M
[--]  +-- KB Used Size :1.5M
[--]  +-- 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.
[--] InnoDB Thread Concurrency: 0
[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 / 160.0K
[!!] Ratio InnoDB redo log capacity / InnoDB Buffer pool size (75%): 100.0M / 128.0M should be equal to 25%
[OK] InnoDB buffer pool instances: 1
[--] 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.61% (38223 hits / 39158 total)
[!!] InnoDB Write Log efficiency: 89.75% (919 hits / 1024 total)
[OK] InnoDB log waits: 0.00% (0 waits / 105 writes)
 
-------- Aria Metrics ------------------------------------------------------------------------------
[--] Aria Storage Engine not available.
 
-------- 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: ROW
[--] XA support enabled: ON
[--] Semi synchronous replication Master: Not Activated
[--] Semi synchronous replication Slave: Not Activated
[--] This is a standalone server
 
-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    MySQL was started within the last 24 hours: recommendations may be inaccurate
    We will suggest raising the 'join_buffer_size' until JOINs not using indexes are found.
             See https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_join_buffer_size
    Be careful, increasing innodb_redo_log_capacity means higher crash recovery mean time
Variables to adjust:
    join_buffer_size (> 256.0K, or always use indexes with JOINs)
    innodb_redo_log_capacity should be (=32M) if possible, so InnoDB Redo log Capacity equals 25% of buffer pool size.

helpは下記

root@6c0e91324465:/tmp# perl mysqltuner.pl --help
Name:
     MySQLTuner 2.3.2 - MySQL High Performance Tuning Script

Important Usage Guidelines:
    To run the script with the default options, run the script without
    arguments Allow MySQL server to run for at least 24-48 hours before
    trusting suggestions Some routines may require root level privileges
    (script will provide warnings) You must provide the remote server's
    total memory when connecting to other servers

Connection and Authentication:
     --host <hostname>           Connect to a remote host to perform tests (default: localhost)
     --socket <socket>           Use a different socket for a local connection
     --port <port>               Port to use for connection (default: 3306)
     --protocol tcp              Force TCP connection instead of socket
     --user <username>           Username to use for authentication
     --userenv <envvar>          Name of env variable which contains username to use for authentication
     --pass <password>           Password to use for authentication
     --passenv <envvar>          Name of env variable which contains password to use for authentication
     --ssl-ca <path>             Path to public key
     --mysqladmin <path>         Path to a custom mysqladmin executable
     --mysqlcmd <path>           Path to a custom mysql executable
     --defaults-file <path>      Path to a custom .my.cnf
     --defaults-extra-file <path>      Path to an extra custom config file
     --server-log <path>         Path to explicit log file (error_log)

Performance and Reporting Options:
     --skipsize                  Don't enumerate tables and their types/sizes (default: on)
                                 (Recommended for servers with many tables)
     --json                      Print result as JSON string
     --prettyjson                Print result as JSON formatted string
     --skippassword              Don't perform checks on user passwords (default: off)
     --checkversion              Check for updates to MySQLTuner (default: don't check)
     --updateversion             Check for updates to MySQLTuner and update when newer version is available (default: don't check)
     --forcemem <size>           Amount of RAM installed in megabytes
     --forceswap <size>          Amount of swap memory configured in megabytes
     --passwordfile <path>       Path to a password file list (one password by line)
     --cvefile <path>            CVE File for vulnerability checks
     --outputfile <path>         Path to a output txt file
     --reportfile <path>         Path to a report txt file
     --template   <path>         Path to a template file
     --dumpdir <path>            Path to a directory where to dump information files
     --feature <feature>         Run a specific feature (see FEATURES section)
    =head1 OUTPUT OPTIONS

     --silent                    Don't output anything on screen
     --verbose                   Print out all options (default: no verbose, dbstat, idxstat, sysstat, tbstat, pfstat)
     --color                     Print output in color
     --nocolor                   Don't print output in color
     --nogood                    Remove OK responses
     --nobad                     Remove negative/suggestion responses
     --noinfo                    Remove informational responses
     --debug                     Print debug information
     --noprocess                 Consider no other process is running
     --dbstat                    Print database information
     --nodbstat                  Don't print database information
     --tbstat                    Print table information
     --notbstat                  Don't print table information
     --colstat                   Print column information
     --nocolstat                 Don't print column information
     --idxstat                   Print index information
     --noidxstat                 Don't print index information
     --nomyisamstat              Don't print MyIsam information
     --sysstat                   Print system information
     --nosysstat                 Don't print system information
     --nostructstat              Don't print table structures information
     --pfstat                    Print Performance schema
     --nopfstat                  Don't print Performance schema
     --bannedports               Ports banned separated by comma (,)
     --server-log                Define specific error_log to analyze
     --maxportallowed            Number of open ports allowable on this host
     --buffers                   Print global and per-thread buffer values

参考

おわりに

MySQLTunerは業務で一回使ってみたが、有効活用できなかった・・・。
どこかで有効活用できればという意味も込めて備忘録を含めて記事にしたので、今後チューニングすることがあれば活用していきたい。

Hugo で構築されています。
テーマ StackJimmy によって設計されています。