Mysql server has gone away

MySQL connect timeout in PHP config

Have a look in your php.ini config file. You’ll find MySQL configuration options. Make sure the mysql.connect_timeout setting isn’t set lower than MySQL wait_timeout, discussed above. The PHP option mysql.connect_timeout is not only used for connect timeout. It’s also when waiting for the first response from the MySQL server. Try increasing mysql.connect_timeout to match or exceed your MySQL wait_timeout and make sure that mysql.allow_persistent is on (default = enabled).

mysql.connect_timeout=90
mysql.allow_persistent=1

IMPORTANT: Read first about PHP Persistent Database Connections to understand the benefits and caveats.

“PHP, by default, sets a read timeout of 60s for streams. This is set via php.ini, default_socket_timeout. This default applies to all streams that set no other timeout value. mysqlnd does not set any other value and therefore connections of long running queries can be disconnected after default_socket_timeout seconds resulting in an error message 2006 – MySQL Server has gone away.”

default_socket_timeout=90

To be throughout, also adjust max_execution_time and max_input_time still in php.ini, if necessary. If PHP’s execution time is longer than max_execution_time, then MySQL server might disconnect.

max_execution_time = 90
max_input_time = 90

MySQL innodb_log_file_size

You may need to increase the innodb_log_file_size MySQL variable in your my.cnf configuration. MySQL’s innodb_log_file_size should be 25% of innodb_buffer_pool_size (if possible, no less than 20%). Keep in mind that the larger this value, the longer it will take to recover from a database crash. (Source: Phpmyadmin Advisor)

This means for example: if your buffer pool size is set to innodb_buffer_pool_size=16G and your  setting is still set to the recommended default of 2 files (innodb_log_files_in_group=2), then your  should be set to 2G. This will create two (2) log files at 2GB each, which equals 25% of innodb_buffer_pool_size=16G.

WARNING: You must stop MySQL server in order to change innodb_log_file_size or innodb_log_files_in_group. If you don’t, you risk catastrophe! (Read: MySQL Log Redo instructions.)

How to fix the mysql error?

Well you as a client, you will need to make sure that your php mysql connection timeout and tcp connection timeout is high enough for the query you are running to complete. You can do this by adding in your script the following:

PHP

ini_set(‘mysql.connect_timeout’, 300);
ini_set(‘default_socket_timeout’, 300);

1
2

ini_set(‘mysql.connect_timeout’,300);

ini_set(‘default_socket_timeout’,300);

This will increase the timeout to 300 seconds. If you need more, you can increase it, but 300 seconds I believe is more than enough, else try splitting the query.

Then for administrator, you would normally set the mysql settings timeout, you would fiddle with the variable

wait_timeout

1 wait_timeout

You can also view the mysql variables by issuing command:

mysqladmin variables

1 mysqladmin variables

Another option you would look after is the max_allowed_packet, if the amount of query is higher than this value, you will also see this error once again. The default value is set to 1MB, keep in mind you would also need to update this value on the client side too, for eg:

~# mysql —max_allowed_packet=32M
~# mysqld —max_allowed_packet=32M

1
2

~# mysql —max_allowed_packet=32M

~# mysqld —max_allowed_packet=32M

For mysql server and client you will also have to add the same value to my.cnf file, so do not forget about that.

The last cause would be the TCP connection timeout, normally this would only happen on Windows where in some cases you do not get an error from your OS when trying to write to your TCP/IP connection.

The solution for this is to use mysql_ping() on the connection to check if connection is active, this would then have the connection re-established and this error would then go away.

More information here:

Well that’s about it I believe, if I remember something else, I’ll be sure to add here. Happy coding!

Справочное руководство по MySQL

A.2.1 Ошибка Access denied A.2.3 Ошибка Can’t connect to MySQL server

Все изложенное в данном разделе относится также и к родственной ошибке
Lost connection to server during query.

Наиболее часто ошибка MySQL server has gone away возникает в
результате тайм-аута соединения и его закрытия сервером. По умолчанию
сервер закрывает соединение по прошествии 8 часов бездействия. Можно
изменить лимит времени, установив при запуске mysqld переменную
wait_timeout.

Другой распространенной причиной получения ошибки MySQL server has gone
away является выдача команды «закрытия» на соединении MySQL с последующей
попыткой выполнить запрос на закрытом соединении.

Если это получено в скрипте, то достаточно просто повторить запрос от
клиента, чтобы соединение автоматически восстановилось.

Обычно в этом случае выдаются следующие коды ошибки (какой из них вы
получите, зависит от ОС):

Код ошибки Описание
CR_SERVER_GONE_ERROR Клиент не может послать запрос серверу.
CR_SERVER_LOST Клиент не получил ошибки при передаче запроса серверу, но
он не получил также полного ответа (или хоть какого-то ответа) на запрос.

Ошибка будет также выдана, если кто-нибудь уничтожит выполняющийся поток
посредством kill номерпотока.

Проверить, что MySQL на ходу, можно, запустив mysqladmin version и изучив
время работы (uptime). Если проблема в аварийном завершении mysqld, то
необходимо сосредоточиться на поиске причины аварии. В этом случае следует
сначала проверить, не будет ли уничтожен MySQL снова при повторном задании
запроса (see section A.4.1 Что делать, если работа MySQL сопровождается постоянными сбоями).

Эти ошибки будут также выдаваться при посылке серверу неверного или
слишком длинного запроса. Если mysqld получает неправильный или слишком
большой пакет, то сервер предполагает, что с клиентом что-то не так, и
закрывает соединение. Если необходимо выполнять объемные запросы
(например, при работе с большими столбцами типа BLOB), можно увеличить
предельный размер запроса, запустив mysqld с опцией -O
max_allowed_packet=# (по умолчанию 1 Mб). Дополнительная память выделяется
по требованию, так что mysqld будет использовать больше памяти только в
случае, когда выдан большой запрос или когда mysqld должен возвратить
большую строку результата!

Если у вас возникнет желание сделать отчет об ошибке по этой проблеме, то
не забудьте включить в него следующие сведения:

  • Информацию о том, упал MySQL или нет (это можно определить по файлу
    hostname.err (see section A.4.1 Что делать, если работа MySQL сопровождается постоянными сбоями).

  • Если определенный запрос уничтожает mysqld, а используемые в нем
    таблицы перед выполнением запроса проверялись с помощью CHECK TABLE,
    то желательно составить контрольный тест (see section E.1.6 Создание контрольного примера при повреждении таблиц).

  • Значение переменной wait_timeout в сервере (это значение выдает
    mysqladmin variables).

  • Информацию о том, пробовали ли вы запускать mysqld с —log и
    проверять, появляется ли выданный запрос в журнале.

Обращайтесь к разделу See section 1.8.1.2 Как задавать вопросы и направлять сообщения об ошибках.

A.2.1 Ошибка Access denied A.2.3 Ошибка Can’t connect to MySQL server

Other causes of MySQL server has gone away

Remote MySQL connections

Remember earlier I mentioned that the error, at times, is only an indication of a deeper underlying issue. For example, remote MySQL connections to . Using a 3rd party payment processing plugin for osCommerce, Magento, etc.

Exceeding MySQL max_connections setting

The maximum permitted number of simultaneous client connections is set by max_connections. Be careful with this setting!! Exhaustion of memory and other resources can occur when set too large and scheduling overhead also increases. As a guide, set max_connections to approximately double the previous number of maximum simultaneous client connections. Eg. if after a month of uptime, maximum simultaneous client connections was 114, then set to max_connections=250. Before you go crazy with this setting please read: How MySQL Handles Client Connections.

Still unresolved? See MySQL’s help page

Oracle has put together a nice self-help page for MySQL server has gone away errors. On that page, they also suggest that you make sure MySQL didn’t stop/restart during the query. Excerpt:

“You can check whether the MySQL server died and restarted by executing mysqladmin version and examining the server’s uptime. If the client connection was broken because mysqld crashed and restarted, you should concentrate on finding the reason for the crash.”

# mysqladmin version
mysqladmin Ver 9.1 Distrib 10.1.40-MariaDB, for Linux on x86_64
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Server version 10.1.40-MariaDB
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/lib/mysql/mysql.sock
Uptime: 20 days 11 hours 49 min 40 sec

Threads: 5 Questions: 1030744326 Slow queries: 3343 Opens: 3585 Flush tables: 1 Open tables: 2564 Queries per second avg: 582.150
# mysqladmin status
Uptime: 1770590 Threads: 4 Questions: 1030752268 Slow queries: 3343 Opens: 3585 Flush tables: 1 Open tables: 2564 Queries per second avg: 582.151

I hope this helps!

Related articles:

MySQL server has gone away error log examples

Keep in mind that this error can be logged in a few ways, as listed below. In addition, at times the error is only an indication of a deeper underlying issue. Meaning the error could be due to a problem or bug in your connecting application or remote service. In which case, you need to check ALL related error logs with the same timestamp, to determine whether another issue may be to blame. Application Performance Monitoring solutions and PHP Stack trace tools can be of help. With this in mind, here are error log examples of the MySQL server has gone away error:

General error: 2006 MySQL server has gone away
Error Code: 2013. Lost connection to MySQL server during query
Warning: Error while sending QUERY packet
PDOException: SQLSTATE: General error: 2006 MySQL server has gone away

MySQL wait_timeout

The reason for MySQL server has gone away error, is often because MySQL’s wait_timeout was exceeded. MySQL wait_timeout is the number of seconds the server waits for activity on a non-interactive connection before closing it. You should make sure the wait_timeout is not set too low. The default for MySQL is 28800 seconds. Often, it gets lowered arbitrarily. That said, the lower you can set wait_timeout without affecting database connections, can be a good sign of MySQL database efficiency. Also, check the variables: ,  and . Adjust or add the following lines in my.cnf to meet your requirements:

wait_timeout=90
net_read_timeout=90
net_write_timeout=90
interactive_timeout=300
connect_timeout=90
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *