Quizás, una de los apartados más críticos en la configuración de un servidor, es la optimización de MySQL.
El quedarse corto o pasarse, significará el desaprovechar recursos, quitándoselos a otras tareas o quedarse corto y que el servidor vaya muy lento e incluso caiga.
Quizás es una de las tareas más tediosas que hay.
He estado buscando durante mucho tiempo algo que me facilitara la vida para optimizar MySQL tanto en mis servidores como en los VPS, Servidores Híbridos y Dedicados de mis clientes.
Normalmente, hay que ir haciendo ajustes en estos para que estén al 100%, no es realizarlo una vez y te olvidas de por vida. SI las necesidades de estos disminuyen o aumentan, hay que ajustarlos de nuevo.
La pesadilla, siempre a sido referente a MySQL.
Después de buscar mucho tiempo, he encontrado un script que es una auténtica maravilla.
El script lo encontrareis en esta página:
Si tenis un VPS o Dedicado, os facilitará la vida muchísimo.
Las instrucciones que voy a dar, son referentes a una instalación en CentOS.
Sirve si tenéis instalado cPanel en él.
Lo primero que deberemos hacer es acceder al servidor por SSH
Una vez que estemos conectados, escribimos:
1 | wget http://www.day32.com/MySQL/tuning-primer.sh |
Con esto, nos descargaremos el script
Para que funcione bien este script, deberemos tener instalado bc, por lo tanto, escribiremos:
1 | yum install bc |
Lo anterior nos instalará bc.
Una vez que lo tengamos instalado, escribimos:
1 | sh tuning-primer.sh |
Debemos estar en el mismo directorio que el archivo.
El script se pondrá en marcha.
Os aconsejo que abráis otra conexión SSH, de esta forma, en una tendréis el script y en la otra podremos configurar MySQL.
Cuando el script finalice, os mostrará algo así (os pongo una imagen, ya que es mucho más clarificadora por los colores):
Y aquí el texto completo que nos muestra:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | -- MYSQL PERFORMANCE TUNING PRIMER --- By: Matthew Montgomery -MySQL Version 5.0.90-community x86_64Uptime = 0 days 14 hrs 6 min 16 secAvg. qps = 2Total Questions = 102107Threads Connected = 2Warning: Server has not been running for at least 48hrs.It may not be safe to use these recommendationsTo find out more information on how each of theseruntime variables effects performance visit:http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.htmlVisit http://www.mysql.com/products/enterprise/advisors.htmlfor info about MySQL's Enterprise Monitoring and Advisory ServiceSLOW QUERIESThe slow query log is NOT enabled.Current long_query_time = 10 sec.You have 4 out of 102128 that take longer than 10 sec. to completeYour long_query_time seems to be fineBINARY UPDATE LOGThe binary update log is NOT enabled.You will not be able to do point in time recoverySee http://dev.mysql.com/doc/refman/5.0/en/point-in-time-recovery.htmlWORKER THREADSCurrent thread_cache_size = 1024Current threads_cached = 5Current threads_per_sec = 0Historic threads_per_sec = 0Your thread_cache_size is fineMAX CONNECTIONSCurrent max_connections = 100Current threads_connected = 3Historic max_used_connections = 8The number of used connections is 8% of the configured maximum.You are using less than 10% of your configured max_connections.Lowering max_connections could help to avoid an over-allocation of memorySee "MEMORY USAGE" section to make sure you are not over-allocatingNo InnoDB Support Enabled!MEMORY USAGEMax Memory Ever Allocated : 542 MConfigured Max Per-thread Buffers : 400 MConfigured Max Global Buffers : 510 MConfigured Max Memory Limit : 910 MPhysical Memory : 31.37 GMax memory limit seem to be within acceptable normsKEY BUFFERCurrent MyISAM index space = 73 MCurrent key_buffer_size = 250 MKey cache miss rate is 1 : 58Key buffer free ratio = 81 %Your key_buffer_size seems to be fineQUERY CACHEQuery cache is enabledCurrent query_cache_size = 250 MCurrent query_cache_used = 14 MCurrent query_cache_limit = 4 MCurrent Query cache Memory fill ratio = 5.73 %Current query_cache_min_res_unit = 4 KYour query_cache_size seems to be too high.Perhaps you can use these resources elsewhereMySQL won't cache query results that are larger than query_cache_limit in sizeSORT OPERATIONSCurrent sort_buffer_size = 1 MCurrent read_rnd_buffer_size = 768 KSort buffer seems to be fineJOINSCurrent join_buffer_size = 1.00 MYou have had 11 queries where a join could not use an index properlyYou should enable "log-queries-not-using-indexes"Then look for non indexed joins in the slow query log.If you are unable to optimize your queries you may want to increase yourjoin_buffer_size to accommodate larger joins in one pass.Note! This script will still suggest raising the join_buffer_size whenANY joins not using indexes are found.OPEN FILES LIMITCurrent open_files_limit = 8302 filesThe open_files_limit should typically be set to at least 2x-3xthat of table_cache if you have heavy MyISAM usage.You currently have open more than 75% of your open_files_limitYou should set a higher value for open_files_limit in my.cnfTABLE CACHECurrent table_cache value = 4096 tablesYou have a total of 13106 tablesYou have 4096 open tables.Current table_cache hit rate is 6%, while 100% of your table cache is in useYou should probably increase your table_cacheTEMP TABLESCurrent max_heap_table_size = 32 MCurrent tmp_table_size = 32 MOf 1472 temp tables, 43% were created on diskPerhaps you should increase your tmp_table_size and/or max_heap_table_sizeto reduce the number of disk-based temporary tablesNote! BLOB and TEXT columns are not allow in memory tables.If you are using these columns raising these values might not impact yourratio of on disk temp tables.TABLE SCANSCurrent read_buffer_size = 1 MCurrent table scan ratio = 32 : 1read_buffer_size seems to be fineTABLE LOCKINGCurrent Lock Wait ratio = 1 : 696You may benefit from selective use of InnoDB.If you have long running SELECT's against MyISAM tables and performfrequent updates consider setting 'low_priority_updates=1'If you have a high concurrency of inserts on Dynamic row-length tablesconsider setting 'concurrent_insert=2'. |
Cómo podéis ver, lo que hace es hacer un estudio de como ha estado funcionando MySQL y da consejos sobre parámetros que debemos tocar.
Una vez que nos muestra el resultado, deberemos realizar las modificaciones aconsejadas por el script.
Para ello, en la otra ventana que tenemos una conexión activa SSH escribimos:
1 | cp /etc/my.cnf /etc/my.cnfBACKUP |
Con lo anterior realizamos una copia de seguridad que no está de más.
1 | vi /etc/my.cnf |
Esto nos abrirá el archivo de configuración de MySQL.
Lo abro con vi, ya que es el que más me gusta, pero podéis realizar las modificaciones con el que más os guste.
Una vez abierto, para los que no estén familiarizados con vi, debéis apretar en el teclado la tecla “Insert”, de esta forma podréis escribir en el archivo.
Realizar las modificaciones que os aconseje el script.
Una vez que las hayáis realizado, apretar el botón “Escape” y escribir:
:w
Esto guardará las modificaciones.
Una vez realizadas las modificaciones, apretar:
:q
Lo anterior os sacará del editor.
Una cosa importante, ya que hay veces que sucede.
Si borras más cosas de la cuenta y no sabes que has borrado, lo mejor es que salgas sin guardar. Para salir sin guardar debéis escribir:
:q!
Acordaros de apretar la tecla “escape” antes, o no tendrá efecto, estaréis escribiendo el el archivo.
Una vez que hayáis realizado los cambios y los hayáis guardado, hay que reiniciar el servidor MySQL.
Si usáis WHM/cPanel, ir a WHM y en “Restart Services” Apretar sobre “SQL Server (MySQL)”
Si no usais WHM, escribir en la consola:
1 | /etc/init.d/mysqld restart |
Si MySQL no reinicia, algo habéis hecho mal en el archivo de configuración.
Para resolverlo y que no nos caigan gotas de sudor, escribimos:
1 | rm –rf /etc/my.cnf |
1 | cp /etc/my.cnfBACKUP /etc/my.cnf |
y volvemos a reiniciar.
Si no habíamos cometido ningún error, casi con toda seguridad la página os irá mucho más fluida.
Ahora, esperáis de 24 a 48h y volvéis a poner en marcha el script y veis resultados.
Si todo sale Ok, perfecto, si os sale algún otro consejo, pues volvéis a realizar el proceso.
FUENTE: http://www.bp-es.com/noticias/2010/05/18/optimiza-mysql-facilmente-sin-ser-un-experto/
