Skip to content
Home » MySQLTuner.pl: La herramienta clásica para optimizar el rendimiento de MySQL/MariaDB

MySQLTuner.pl: La herramienta clásica para optimizar el rendimiento de MySQL/MariaDB

MySQLTuner.pl es un script en Perl de código abierto, ligero y muy popular entre administradores de bases de datos. Analiza de forma rápida la configuración y el estado de un servidor MySQL, MariaDB o Percona Server, y genera recomendaciones concretas para mejorar el rendimiento y la estabilidad.

Aunque existen herramientas más modernas (como Percona Toolkit o dashboards con Prometheus + Grafana), MySQLTuner sigue siendo una referencia clásica por su simplicidad y efectividad.¿Qué hace exactamente MySQLTuner?

  • Revisa variables de configuración (my.cnf/my.ini).
  • Analiza estadísticas en tiempo real (uso de memoria, caché, consultas lentas, etc.).
  • Evalúa el uso de motores de almacenamiento (InnoDB, MyISAM, Aria…).
  • Detecta posibles problemas de seguridad.
  • Sugiere ajustes de variables y buenas prácticas.
  • Proporciona un puntaje de salud (Weighted Health Score) en versiones recientes.

Requisitos

  • Perl instalado (perl).
  • Acceso a un usuario con privilegios suficientes (idealmente root de MySQL).
  • El servidor MySQL debe haber estado funcionando al menos 24-48 horas para que las estadísticas sean representativas.

Instalación (método recomendado)

# Descargar la última versión
wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/mysqltuner.pl -O mysqltuner.pl

# (Opcional) Descargar archivos auxiliares para más funcionalidades
wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/basic_passwords.txt
wget https://raw.githubusercontent.com/major/MySQLTuner-perl/master/vulnerabilities.csv

# Dar permisos de ejecución
chmod +x mysqltuner.pl

En distribuciones Debian/Ubuntu también puedes instalarlo vía paquetes:

sudo apt update && sudo apt install mysqltuner

Cómo usarloUso básico (local):

./mysqltuner.pl
# o
perl mysqltuner.pl

Te pedirá usuario y contraseña de MySQL.Uso con credenciales directas:

./mysqltuner.pl --user root --pass TU_CONTRASEÑA

Otras opciones útiles:

OpciónDescripción
–host / –portConexión remota
–verboseMás información detallada
–buffers / –dbstat / –idxstatEstadísticas específicas
–cvefile=vulnerabilities.csvChequeo de vulnerabilidades conocidas
–nocolorSalida sin colores (útil para cron)
–outputfile archivo.txtGuardar resultado en archivo

Ejemplo de salida y cómo interpretarla

El informe se divide en varias secciones clave:

  1. Storage Engine Statistics — Muestra uso de InnoDB, MyISAM, tablas fragmentadas, etc.
  2. Security Recommendations — Usuarios sin contraseña, privilegios excesivos…
  3. Performance Metrics — Uso de memoria, hit ratio de cachés, consultas lentas, etc.
  4. Recommendations — Aquí está el oro: sugerencias generales y variables a ajustar.

Ejemplo de recomendaciones típicas:

General recommendations:
    Run OPTIMIZE TABLE on fragmented tables
    Enable the slow query log
    Reduce or eliminate unclosed connections

Variables to adjust:
    innodb_buffer_pool_size (> 4G)          # Muy importante en InnoDB
    query_cache_size (=0)                   # Desactivado en MySQL 8+
    max_connections (> 151)
    table_open_cache (> 2000)
    innodb_log_file_size (>= 1G)

Las recomendaciones más comunes e importantes

  • innodb_buffer_pool_size: Debe ser el 60-80% de la RAM disponible si el servidor está dedicado a la base de datos (¡el ajuste más importante!).
  • table_open_cache y table_definition_cache: Aumentar si hay muchas tablas.
  • max_connections: Ajustar según el número real de conexiones simultáneas.
  • query_cache: En MySQL 8+ está deprecado; mejor desactivarlo.
  • slow_query_log + long_query_time=1: Actívalo siempre para detectar consultas problemáticas.
  • tmp_table_size y max_heap_table_size: Evitar que se creen tablas temporales en disco.

Mejores prácticas al aplicar cambios

  1. Nunca apliques todo ciegamente. Entiende cada cambio.
  2. Cambia una variable a la vez, reinicia MySQL y mide el impacto.
  3. Ejecuta MySQLTuner después de 24-48 horas de carga real.
  4. Haz backup de tu my.cnf antes de modificar.
  5. Usa herramientas complementarias: pt-query-digest (Percona Toolkit), EXPLAIN, Monitoring (MySQL Workbench, PMM, etc.).
  6. Reinicia el servicio: systemctl restart mysql o mariadb.

Ejemplo de configuración básica optimizada (para servidor dedicado 8-16 GB RAM)

[mysqld]
innodb_buffer_pool_size = 6G
innodb_log_file_size = 1G
innodb_log_buffer_size = 256M
table_open_cache = 4000
max_connections = 300
query_cache_type = 0
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1

MySQLTuner.pl es una herramienta rápida, fiable y todavía vigente en 2026. No reemplaza un buen monitoreo continuo ni el conocimiento profundo de MySQL, pero es excelente para:

  • Auditorías rápidas
  • Diagnóstico inicial de problemas de rendimiento
  • Servidores de desarrollo y producción

Ejemplo práctico

Supongamos que tenemos la siguiente respuesta tras analizar MariaDB:

# ./mysqltuner.pl
 >>  MySQLTuner 2.8.41
         * 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
Please enter your MySQL administrative login: root
Please enter your MySQL administrative password:
✔  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: 1.1G (Tables: 934)
ℹ  Data in MyISAM tables: 518.6M (Tables: 73)
✔  Total fragmented tables: 0

✔  Currently running supported MySQL/MariaDB version 11.8.6-MariaDB(LTS)

-------- Log file Recommendations ------------------------------------------------------------------
✔  Log journal` systemd:mariadb.service exists
✘  systemd:mariadb.service contains 8979 warning(s).
✘  systemd:mariadb.service contains 90 error(s).
ℹ  2 start(s) detected in systemd:mariadb.service
ℹ  1) Apr 14 09:57:07 obelix4 mariadbd[1996842]: 2026-04-14  9:57:07 0 [Note] /usr/sbin/mariadbd: ready for connections.
ℹ  2) Apr 14 08:58:48 obelix4 mariadbd[1993541]: 2026-04-14  8:58:48 0 [Note] /usr/sbin/mariadbd: ready for connections.
ℹ  0 shutdown(s) detected in systemd:mariadb.service

-------- Analysis Performance Metrics --------------------------------------------------------------
ℹ  innodb_stats_on_metadata: OFF
✔  No stat updates during querying INFORMATION_SCHEMA.

-------- Views Metrics -----------------------------------------------------------------------------

-------- Triggers Metrics --------------------------------------------------------------------------

-------- Routines Metrics --------------------------------------------------------------------------

-------- Security Recommendations ------------------------------------------------------------------
ℹ  -- Please help get to 10k stars at https://github.com/MariaDB/Server - 11.8.6-MariaDB
✘  User ''@'localhost' is an anonymous account. Remove with DROP USER ''@'localhost';
✔  All database users have passwords assigned
✘  There is no basic password file list!

-------- SSL/TLS Security Recommendations ----------------------------------------------------------
✔  Current connection is encrypted (TLS_AES_256_GCM_SHA384)
✔  SSL support is enabled
✘  require_secure_transport is OFF
✔  Only secure TLS versions enabled: TLSv1.2,TLSv1.3
✘  No SSL certificates configured (ssl_cert/ssl_key are empty)
✔  All remote users have SSL enforcement active (or no remote users exist)

-------- CVE Security Recommendations --------------------------------------------------------------
ℹ  Skipped: --cvefile option not specified

-------- Performance Metrics -----------------------------------------------------------------------
ℹ  Up for: 2d 22h 53m 16s (23M q [92.267 qps], 227K conn, TX: 305G, RX: 9G)
ℹ  Reads / Writes: 96% / 4%
ℹ  Binary logging is disabled
ℹ  Physical Memory     : 31.3G
ℹ  Max MySQL memory    : 861.2M
ℹ  Other process memory: 0B
ℹ  Total buffers: 417.0M global + 2.9M per thread (151 max threads)
ℹ  Performance_schema Max memory usage: 0B
ℹ  Galera GCache Max memory usage: 0B
✔  Maximum reached memory usage: 549.4M (1.71% of installed RAM)
✔  Maximum possible memory usage: 861.2M (2.69% of installed RAM)
✔  Overall possible memory usage with other process is compatible with memory available
✔  Slow queries: 0% (2K/23M)
✔  Highest usage of available connections: 29% (45/151)
✔  Aborted connections: 0.64% (1449/227077)
✘  Name resolution is active: a reverse name resolution is made for each new connection which can reduce performance
✔  Query cache is disabled by default due to mutex contention on multiprocessor machines.
✔  Sorts requiring temporary tables: 0% (0 temp sorts / 4M sorts)
✘  Joins performed without indexes: 14258
✘  Temporary tables created on disk: 41% (714K on disk / 1M total)
✔  Thread cache hit rate: 99% (82 created / 227K connections)
✔  Table cache hit rate: 99% (24M hits / 24M requests)
✘  table_definition_cache (400) is less than number of tables (1306)
✔  Open file limit used: 1% (356/32K)
✔  Table locks acquired immediately: 99% (20M immediate / 20M locks)

-------- InnoDB Metrics ----------------------------------------------------------------------------
ℹ  InnoDB is enabled.
✘  InnoDB variable 'have_innodb' is removed in MariaDB 10.0.0.
✘  InnoDB variable 'innodb_prefix_index_cluster_optimization' is removed in MariaDB 10.10.0.

-------- Smart Migration LTS Advisor ---------------------------------------------------------------
✘  Found 1 potential migration risks.
ℹ   - [Migration Risk] sql_mode: NO_AUTO_CREATE_USER is removed in modern versions. Ensure your scripts do not rely on it.
✔  InnoDB File per table is activated
✔  InnoDB Buffer Pool size ( 128.0M ) under limit for 64 bits architecture: (17179869184.0G )
✘  InnoDB buffer pool / data size: 128.0M / 1.1G
ℹ  innodb_buffer_pool_chunk_size is set to 'autosize' (0) in MariaDB >= 10.8. Skipping chunk size checks.
✔  InnoDB Read buffer efficiency: 99.89% (52585510 hits / 52644088 total)
✘  InnoDB Write Log efficiency: 84.26% (882335 hits / 1047180 total)
✔  InnoDB log waits: 0.00% (0 waits / 164845 writes)

-------- InnoDB Transactions -----------------------------------------------------------------------
ℹ  Transaction Isolation Level: REPEATABLE-READ
ℹ  InnoDB Snapshot Isolation: ON
ℹ  Active InnoDB Transactions: 0

-------- Infrastructure-Aware InnoDB Tuning --------------------------------------------------------
ℹ  Detected Storage Type: HDD
✔  innodb_flush_neighbors is enabled for HDD: 1

-------- Query Cache Information -------------------------------------------------------------------
ℹ  QUERY_CACHE_INFO plugin is not active or not installed.

-------- Query Anti-Pattern Detection (Experimental) -----------------------------------------------
ℹ  Skipped: Performance Schema is disabled.

-------- Aria Metrics ------------------------------------------------------------------------------
ℹ  Aria Storage Engine is enabled.
✔  Aria pagecache size / total Aria indexes: 128.0M/352.0K
✔  Aria pagecache hit rate: 99.7% (9M cached / 23K 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

-------- Predictive Capacity Planning --------------------------------------------------------------
✔  Memory headroom: 37.9G (Theoretical max usage is 2.69% of physical RAM)
ℹ  Growth forecasting: Insufficient uptime (< 24h) for reliable estimation.

-------- Security Hardening 2.0 --------------------------------------------------------------------
ℹ  TLS/SSL is enabled. Minimum supported TLS version: TLSv1.2,TLSv1.3

-------- Guided Auto-Fix Snippets ------------------------------------------------------------------
Ready-to-Apply SQL Snippets (SET GLOBAL):

Ready-to-Apply Configuration Block ([mysqld]):
    skip-name-resolve=ON
    join_buffer_size (> 256.0K, or always use indexes with JOINs)
    tmp_table_size (> 16M)
    max_heap_table_size (> 16M)
    table_definition_cache (400) > 1306 or -1 (autosizing if supported)
    innodb_buffer_pool_size (>= 1.1G) if possible.
    innodb_log_buffer_size (> 16M)

-------- Health Score KPI --------------------------------------------------------------------------
Overall Weighted Health Score: 75/100
ℹ  Your database health is good, but there's room for improvement.


-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Check warning line(s) in systemd:mariadb.service file
    Check error line(s) in systemd:mariadb.service file
    Remove Anonymous User accounts: there are 1 anonymous accounts.
    Enable require_secure_transport to force all connections to use SSL.
    Configure SSL certificates (ssl_cert, ssl_key, ssl_ca) to enable encrypted connections.
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=ON
    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
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries which have no LIMIT clause
    Remove 'have_innodb' from your configuration. Replaced by checking INFORMATION_SCHEMA.PLUGINS or SHOW ENGINES.
    Remove 'innodb_prefix_index_cluster_optimization' from your configuration. Always enabled.
    Migration Risk (sql_mode): NO_AUTO_CREATE_USER is removed in modern versions. Ensure your scripts do not rely on it.
Variables to adjust:
    skip-name-resolve=ON
    join_buffer_size (> 256.0K, or always use indexes with JOINs)
    tmp_table_size (> 16M)
    max_heap_table_size (> 16M)
    table_definition_cache (400) > 1306 or -1 (autosizing if supported)
    innodb_buffer_pool_size (>= 1.1G) if possible.
    innodb_log_buffer_size (> 16M)
✔  Terminated successfully

Lo importante es solucionar los problemas críticos, seguridad y rendimiento.

En este caso hay algo crítico relativo a la seguridad que es la existencia de este usuario con acceso total aunque todas las bases de datos están con su usurio único.

Luego hay una parte muy interesante que nos indica que está lista para apicar directamente:

Ready-to-Apply Configuration Block ([mysqld]):
    skip-name-resolve=ON
    join_buffer_size (> 256.0K, or always use indexes with JOINs)
    tmp_table_size (> 16M)
    max_heap_table_size (> 16M)
    table_definition_cache (400) > 1306 or -1 (autosizing if supported)
    innodb_buffer_pool_size (>= 1.1G) if possible.
    innodb_log_buffer_size (> 16M)