Почему тормозит MySQL сервер?

Здравствуйте. Нужна помощь по устранение тормозов MySQL.

Имеется VDS (KVM) сервер с 768 mb RAM и 2x2.80 GHz CPU. Стоит связка nginx + php-fpm (с xcache). Страницы сайта грузятся быстро, но примерно раз в каждые ~20 начинаются дикие тормоза - страница может генерироваться от 2-х до 17 сек (в среднем - 3 сек). По логам удалось выяснить причину тормозов - это mysql. Сначала предполагал, что проблема в долгом подключении в БД, но включив slow log MySQL'а, оказалось, что тормозит сам сервер БД. В логе фигурируют различные запросы: select, insert, update, delete.

Баз у меня немного, размер не более 100 МБ. Сервер на ОС Debian 6.
mysql status:
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version          5.5.31-1~dotdeb.0-log
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/run/mysqld/mysqld.sock
Uptime:                 11 min 47 sec

Threads: 2  Questions: 15008  Slow queries: 24  Opens: 3789  Flush tables: 1  Open tables: 64  Queries per second avg: 21.227.


Оперативной памяти тоже хватает:
total       used       free     shared    buffers     cached
Mem:           747        661         85          0         25        393
-/+ buffers/cache:        243        503
Swap:            0          0          0


my.cnf:
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port		= 3306
socket		= /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 16M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket		= /var/run/mysqld/mysqld.sock
nice		= 0

[mysqld]
#
# * Basic Settings
#
user		= mysql
pid-file	= /var/run/mysqld/mysqld.pid
socket		= /var/run/mysqld/mysqld.sock
port		= 3306
basedir		= /usr
datadir		= /var/lib/mysql
tmpdir		= /tmp
# lc-message-dir is unknown to MySQL 5.1
#lc-messages-dir	= /usr/share/mysql
skip-name-resolve
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#
# * Fine Tuning
#
key_buffer		= 16M
max_allowed_packet	= 16M
thread_stack		= 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover         = BACKUP
max_connections        = 50
table_cache            = 64
thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit	= 2M
query_cache_size        = 4M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1
#
# Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf.
#
# Here you can see queries with especially long duration
slow_query_log = 1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id		= 1
#log_bin			= /var/log/mysql/mysql-bin.log
expire_logs_days	= 10
max_binlog_size         = 100M
#binlog_do_db		= include_database_name
#binlog_ignore_db	= include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem



[mysqldump]
quick
quote-names
max_allowed_packet	= 16M

[mysql]
#no-auto-rehash	# faster start of mysql but no tab completition

[isamchk]
key_buffer		= 16M

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/
  • Вопрос задан
  • 10591 просмотр
Решения вопроса 1
fornit1917
@fornit1917
MyISAM при записях/апдейтах лочит всю таблицу, что тормозит ВСЕ остальные запросы к этим же таблицам, коих накапливается немало, что может привести к нехилым тормозам системы в целом (если у вас много запросов на модификацию). Ну и вдовесок размеры буферов для MyISAM у вас не шибко большие.
Мой совет - переходите на InnoDB. Если нет возможности, то хотя бы буферы побольше сделайте, но боюсь это особо не поможет.
Ответ написан
Пригласить эксперта
Ответы на вопрос 5
papahoolio
@papahoolio
Ну так dev.mysql.com/doc/refman/5.0/en/slow-query-log.html и профилировать же dev.mysql.com/doc/refman/5.0/en/explain.html select'ы из лога
Ответ написан
Комментировать
IlyaEvseev
@IlyaEvseev
Opensource geek
1) mysqltuner скачайте и запустите. Что он посоветует?

2) про explain для медленных запросов только что сказали.
Ответ написан
Комментировать
@AndreyTM Автор вопроса
Вот, что сказал mysqltuner
f2fcbe04aedd46b9879eaec65bf6f54b17fd1528
Ответ написан
@AndreyTM Автор вопроса
Когда добавляю skip-innodb в секцию [mysqld] - сервер не запускается.
Ответ написан
stavinsky
@stavinsky
Ребят сколько раз повторять, прежде чем лезть в настройки бд, смотрите в ваши запросы.
Slow queries: 24 за 10 минут. Понятное дело что все будет колом стоять. (не в хорошем смысле к сожалению).

Так что включайте slow-log, смотрите в него внимательно, добавляйте/удаляйте индексы по вкусу, переписывайте запросы.

И когда вы перепишете все запросы, и будете уверены что дальше их оптимизировать нельзя, тогда только можно смотреть в сторону всяких mysql-tunner'ов и тд. Хотя откровенно говоря, обычно выручают стандартные конфиги мускула, коих 4 штуки лежит в комплекте с ним. Дело в том что тупое следование рекомендациям без понимания всего процесса работы бд вас не спасет. Скорее вы только получите ухудшение скорости работы.

P.S. Да и еще. phpmyadmin последних версий тоже в советчики заделался. Теперь тоже подсказывает что где подкрутить. Поищите там.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы