The error returned was mysql server has gone away error number 1

Эта ошибка означает, что MySQL сервер запущен, но он отказывает вам в соединении. Это может произойти по нескольким причинам. Самых основных и часто

Эта ошибка означает, что MySQL сервер запущен, но он отказывает вам в соединении. Это может произойти по нескольким причинам. Самых основных и часто встречающихся причин три: сервер перегружен, и у вас истекло время ожидания ответа, ваш клиент отправил слишком большой пакет или сервер был не до конца проинициализирован.

В этой небольшой статье мы рассмотрим более подробно, почему возникает ошибка 2006: MySQL server has gone away, а также — как её исправить.

Такую ошибку вы можете увидеть во время подключения к базе данных с помощью PHP, консольного клиента или, например, в PhpMyAdmin:

1. Истекло время ожидания

Как я уже писал выше, одной из причин может быть таймаут ожидания соединения. Возможно, сервер баз данных перегружен и не успевает обрабатывать все соединения. Вы можете подключиться к серверу с помощью консольного клиента, если вам это удастся, и попытаться выполнить какой-либо запрос, чтобы понять, действительно ли запросы выполняются слишком долго. Если это так, можно оптимизировать производительность MySQL с помощью скрипта MySQLTuner.

В большинстве случаев надо увеличить размер пула движка InnoDB с помощью параметра innodb_buffer_pool_size. Какое значение лучше поставить, можно узнать с помощью указанного выше скрипта. Например, 800 мегабайт:

sudo vi /etc/mysql/my.cnf

innodb_buffer_pool_size=800M

Есть и другой путь решения этой проблемы. Если такая скорость обработки запросов считается нормальной, можно увеличить время ожидания ответа от сервера. Для этого измените значение параметра wait_timeout. Это время в секундах, на протяжении которого надо ждать ответа от сервера. Например:

wait_timeout=600

После любых изменений не забудьте перезапустить MySQL сервер:

sudo systemctl restart mysql

или:

sudo systemctl restart mariadb

2. Слишком большой пакет

Если ваш клиент MySQL создаёт слишком большие пакеты с запросами к серверу, это тоже может стать причиной такой ошибки. Максимально доступный размер пакета можно увеличить с помощью параметра max_allowed_packet. Например:

sudo vi /etc/mysql/my.cnf

max_allowed_packet=128M

Обратите внимание, что если вы из своей программы отправляете большие пакеты, то, скорее всего, вы делаете что-то не так. Не надо генерировать запросы к MySQL с помощью циклов for. SQL — это отдельный язык программирования, который многое может сделать сам, без необходимости писать очень длинные запросы.

3. Сервер неверно проинициализирован

Такая проблема может возникать при разворачивании контейнера MySQL или MariaDB в Docker. Дело в том, что на первоначальную инициализацию контейнера нужно много времени: около нескольких минут. Если вы не дадите контейнеру завершить инициализацию, а остановите его и потом снова запустите, то база данных будет всегда возвращать такую ошибку.

Вам нужно полностью удалить данные контейнера с базой данных. Например, с помощью docker-compose:

docker-compose down

или вручную:

docker rm mysql-container

Здесь mysql-container — это имя контейнера с базой данных. А затем надо удалить хранилище (volume) с некорректно проинициализированной базой. Сначала посмотрите список всех хранилищ:

docker volume ls

Затем удалите нужное:

docker volume rm имя_хранилища

После этого можете снова запускать инициализацию приложения, только на этот раз дождитесь, пока сервер баз данных сообщит, что он готов, и вы сможете к нему подключиться.

Выводы

В этой небольшой статье мы рассмотрели, что значит ошибка MySQL Server has gone away, а также как её исправить на сервере или в контейнере Docker. Вы знаете ещё другие причины и решения этой проблемы? Пишите в комментариях!

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

The MySQL server has gone away error, which means that the MySQL server (mysqld) timed out and closed the connection. By default, MySQL will close connections after eight hours (28800 seconds) if nothing happens. However, in some cases, your web host, DBA, or app developer may have decreased this timeout setting, as discussed below.

MySQL server has gone away, can be a frustrating error to solve. This is partly because, to solve this error, sometimes the solution involves multiple layers, application, or service config changes. This article includes solutions I’ve seen for this MySQL server general error. If you’ve found a solution not listed or linked to on this page, please send me a note or leave a comment.

MySQL server has gone away

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 this 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[HY000]: General error: 2006 MySQL server has gone away

Sponsored: Datadog – View query metrics and explain plans from all of your databases in a single place.
Datadog database metrics
Datadog is a unified monitoring, analytics, and security platform that offers end-to-end monitoring for all of your databases, including MySQL, PostgreSQL, and more! Quickly pinpoint costly, slow queries and troubleshoot performance issues faster with key database metrics and patterns in one place. Easily search, compare, and filter your queries on execution plans to quickly identify areas for performance and cost improvements. Utilize our integrations for MySQL, PostgreSQL, SQL Server, and more to visualize key system performance metrics on an out-of-the-box dashboard alongside query and host-level metrics. Datadog Database Monitoring is closely integrated with the rest of the Datadog platform; further improve your Database performance with other key features such as SLO tracking, monitors & alerts, Security Monitoring, and more!

Cost: Free plan, or starting at $70.

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 wait_timeout 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: net_read_timeoutnet_write_timeout and interactive_timeout. 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

MySQL connect timeout in PHP config.

Have a look at 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.

Also, adjust PHP’s default_socket_timeout. For example, a PHP script could be running a slow query. Creating a wait that utilizes the default_socket_timeout. Eventually, it quits with the “MySQL server has gone away” error. Before you send hate mail, please read here first. Here’s an excerpt:

“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 max_allowed_packet

max_allowed_packet is the maximum size of one packet. The default size of 4MB helps the MySQL server catch large (possibly incorrect) packets. As of MySQL 8, the default has been increased to 16MB. If mysqld receives a packet that is too large, it assumes that something is wrong and closes the connection. To fix this, you should increase the max_allowed_packet in my.cnf, then restart MySQL. The max for this setting is 1GB. For example:

max_allowed_packet = 512M

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%). Remember 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 innodb_log_files_in_group setting is still set to the recommended default of 2 files (innodb_log_files_in_group=2), then your innodb_log_file_size 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.)

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 3rd party services. Using a 3rd party payment processing plugin for osCommerce, Magento, etc.

MySQL database charset and collation

Changing default database charset to latin1 and default collation to latin1_general_ci seemed to have solved MySQL server has gone away for some.

Exceeding MySQL max_connections setting

Max_connections set the maximum permitted number of simultaneous client 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. E.g., if after a month of uptime, the maximum simultaneous client connections were 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 Performance Tuning: Tips, Scripts and Tools
  • Tuning MySQL: my.cnf, avoid this common pitfall!
  • MySQL Performance: Stop hoarding. Drop unused MySQL databases

Published: June 7th, 2019 | Last updated: Nov 10th, 2022

Tags: apm, linux, mariadb, mysql, performance, server, sysadmins

mysql

Две наиболее распространенные причины получения ошибки MySQL server has gone away (error 2006) это..

  1. Сервер закрыл соединение по таймауту.

    Исправить можно так:
    проверить чтобы значение переменной wait_timeout в конфиг файле MySql — my.cnf было достаточным для выполнения скрипта.

    На Debian
    : нужно выполнить

    sudo nano /etc/mysql/my.cnf

    и установить wait_timeout = 600 ( значение задается в секундах, если ошибка не пропадет поиграйтесь с этим значением, чтобы найти оптимальное), после этого нужно рестартануть MySQL:

    sudo /etc/init.d/mysql restart

    Я не проверял, но значение по-умолчанию для wait_timeout можно установить вплоть до 28800 секунд (8 часов).

  2. Сервер сбрасывает (отклоняет) неправильные или слишком большие пакеты. Если mysqld получает пакет данных, который слишком большой или не корректный, он думает что что-то пошло не так или с клиентом случилась какая-то беда и закрывает соединение. Часто такая ошибка возникает при импорте дампов содержащих большие тексты.

    Так же такое происходит, когда у Вас слишком большой запрос. Например, вы хотите в поле типа longtext записать какую-нибудь книгу, в которой текста на 20 мб. Либо хотите сохранить большой файл (например картинку) в поле с типом blob. В итоге у вас получается запрос по типу

    UPDATE books SET text=«сууупер..длинный..текст» WHERE id=1

    Если это Ваш случай, то подумайте действительно ли Вам нужно сохранять такой текст/файл  в базу, обычная практика в таких случаях, сохранить его в файл на диск, а в базу сохранить имя этого файла. Типа того

    file_put_content(‘book.txt’, ‘сууупер..длинный..текст’);

    ...

    UPDATE books SET filename=«book.txt» WHERE id=1


    Исправить можно так:
    вы можете увеличить максимальный размер пакета увеличив значение max_allowed_packet в файле my.cnf.

    На Debian
    нужно выполнить:

    sudo nano /etc/mysql/my.cnf

    и установить max_allowed_packet = 64M (если ошибка не пропадет поиграйтесь с этим значением, чтобы найти оптимальное), после этого нужно рестартануть MySQL

    sudo /etc/init.d/mysql restart

Про max_allowed_packet я так же писал здесь: ERROR 2006 (HY000) — MySQL server has gone away

Если Вы получаете ошибку MySQL server has gone away (error 2006) при использовании драйвера MySQL ODBC – можете попробовать это решение.

Оригинал исходной статьи (на англ): How to fix “MySQL server has gone away” (error 2006)

Похожие статьи

Автор:
| Рейтинг: 5/5 |
Теги:



Debian, Linux, Ubuntu, Windows, Windows 10, Windows 11, Windows 7, Windows 8, Windows Server, Windows Vista, Windows XP

  • 24.11.2021
  • 2 845
  • 0
  • 1
  • 1
  • 0

Исправляем ошибку: MySQL server has gone away

  • Содержание статьи
    • Описание
    • Причины возникновения
    • Как исправить ошибку
      • Разрыв соединения из-за таймаута
      • Разрыв соединения из-за слишком большого размера пакета
      • Закончившаяся память
    • Добавить комментарий

Описание

В данной статье пойдет речь об ошибке, которую можно получить при обращении к MySQL Server:

MySQL server has gone away

Причины возникновения

Наиболее частыми причинами возникновения ошибки являются следующие причины:

  • Слишком долгое неактивное соединение между скриптом/приложением и MySQL сервером (по умолчанию составляет 8 часов, потом разрывается и вылезает эта ошибка)
  • Слишком большой размер пакета при запросе к серверу MySQL (по умолчанию = 16M, если размер пакета больше, например, из-за какого-нибудь BLOB объекта, который превышает данный размер, то вылетает эта ошибка)
  • Закончившаяся оперативная память на сервере с MySQL (проверить можно командой free -h на ОС Linux)

Как исправить ошибку

Разрыв соединения из-за таймаута

Если ваш скрипт или программа устанавливает соединение с MySQL сервером, но после этого ничего не передает, то спустя некоторое время (по умолчанию обычно эта настройка равна 8 часам) сервер просто закрывает соединение и при попытке что-либо записать в базу — получаем ошибку «MySQL server has gone away». Чтобы увеличить таймаут, необходимо внести правки в конфиг MySQL сервера (обычно mysqld.cnf) в секции [mysqld]. В данном примере мы увеличим срок такого таймаута до 24 часов. Для этого вносим следующие настройки в секцию [mysqld]:

# 24 hours
wait_timeout = 86400
# 24 hours
interactive_timeout = 86400

В итоге должно получиться что то подобное:

После этого сохраняем изменения в конфиге и перезапускаем MySQL, чтобы применить настройки.

Разрыв соединения из-за слишком большого размера пакета

В том случае, если у вас очень большие по размеру пакеты (например, какой-нибудь BLOB объект, который хранится в базе, вроде фото, видео и т.п.), то в этом случае MySQL сервер может также выдавать аналогичную ошибку «MySQL server has gone away». Чтобы избавиться от этой ошибки, необходимо увеличит в конфиге максимальный размер пакета. Для этого открываем конфиг MySQL, (обычно mysqld.cnf), ищем в нем опцию max_allowed_packet, которая должна находиться в секции[mysqld] и меняем текущее значение на бОльшее. В нашем примере мы меняем стандартное значение 16M, на 256M. Должно быть как на скриншоте ниже:

После этого сохраняем изменения в конфиге и перезапускаем MySQL, чтобы применить настройки.

Закончившаяся память

Для корректной работы MySQL сервера и любой другой программы требуется оперативная память. Если вы заметили, что у вас выскакивает ошибка «MySQL server has gone away» и в эти моменты на сервере нет свободной оперативной памяти — значит вам надо эту причину каким-либо образом устранить. Отключить лишние сервисы, которые потребляют память, найти другие запущенные процессы, которые потребляют слишком много ресурсов и ограничит их, либо банально увеличить доступную память, путем установки новой планки(ок).

Databases are key components of most modern websites so errors that affect yours tend to be particularly worrisome. The “MySQL server has gone away” error, for example, may make you believe that your database was lost. That means you might have to resort to your latest backup to get your site up and running.

Despite how intimidating it sounds, however, the”MySQL server has gone away” error is pretty easy to fix. In fact, with the right instructions, your website should be back up and running in a matter of minutes.

In this article, we’re going to show you what the “MySQL server has gone away” error looks like and break down what can cause it in WordPress. Then we’ll teach you how to fix it and prevent this error from showing up again in the future.

Let’s get to work!

An Introduction to the “MySQL Server Has Gone Away” Error

First, let’s take a quick look at what the “MySQL server has gone away” error looks like:

MySQL Server Has Gone Away error

Browser showing the “MySQL server has gone away” error

The error itself is pretty straightforward and it almost always appears in the same way. Depending on which browser you use and your server’s configuration, however, the specific wording might change a bit.

As for the error itself, it has to do with your MySQL database, as you might imagine from the name. To be more specific, one of three things usually causes this error on most websites:

  1. There’s a broken table within your database. Your database became corrupted so you need to revert to a recent backup or repair it.
  2. Your PHP ‘timeout’ setting is too low. If a PHP script needs access to your database and it can’t fetch the information within the timeout window that’s been set, this can also trigger the aforementioned error.
  3. ‘Packets’ have either been dropped or are too large. The server deems this to be the case, it essentially closes the connection and throws up the error.

Fortunately, all of these issues can be easily addressed. Let’s talk about how you can start the troubleshooting process.

How to Fix the “MySQL Server Has Gone Away” Error in WordPress (3 Methods)

As we’ve seen, there are a few potential causes for this particular WordPress error.

For that reason, there are different possible solutions. In most cases, one of the fixes below should get rid of the error on your website. So if one doesn’t work, you can simply move on to the next.

1. Edit Your WordPress wp-db.php File

If your website’s PHP timeout setting is too low and your database is too large, fetching the data you need during that window can be a problem. As we mentioned before, this can trigger the “MySQL server has gone away” error.

To prevent that from happening, you’ll need to edit one of your WordPress core files, called wp-db.php. You can find this file within your WordPress root folder, by opening up the wp-includes directory:

The wp-db.php file

The wp-db.php file

For accessing these files, we recommend that you use an FTP client such as FileZilla and connect via SFTP (understand the difference between FTP and SFTP). Once you’ve connected to your site, locate wp-db.php, and right-click on it to open the file using your default local text editor. Follow this quick guide to show all hidden files in Filezilla.

Then, search through the file for the following line:

$this->ready = true;

Add the following line right below that code:

$this->query("set session wait_timeout=300");

What this code does is set your PHP timeout value to 300 seconds, which should be a lot more than you need to prevent any errors from showing up.

Now save the changes to your wp-db.php file and make sure your website is loading as it should.

Please note that if you’re a Kinsta user, you shouldn’t need to alter your website’s PHP timeout settings. All of our plans have a base timeout value of 300 seconds out of the box and we can help you increase it depending on your needs.

2. Repair Your WordPress Database

Sometimes your WordPress database can become corrupted, which in turn can lead to errors when you’re trying to establish a connection with it. This isn’t all that common but it can happen in the course of a normal website’s growth as you add more tables to your database (as well as plugin and theme information).

To fix this issue, you can use a built-in WordPress function to repair your database. First, however, you’ll have to enable that feature. This involves navigating to your WordPress root directory and opening the wp-config.php file in order to edit it.

Once the file is open, scroll to the bottom and add the following line to it:

define('WP_ALLOW_REPAIR', true);

That simple line of code tells WordPress to enable the database repair function. Save the changes to wp-config.php, and close the file. To run the function, just visit the following URL:

https://yourwebsite.com/wp-admin/maint/repair.php

WordPress will then ask if you want to simply repair your database or repair and optimize it. The first option is all you need to fix the “MySQL server has gone away” error:

The repair database option in WordPress

The repair database option in WordPress

The process shouldn’t take long, and when it’s done, the error in question should be gone. However, you still have some cleanup to do, as you’ll need to disable the database repair function on your website. If you don’t, anyone could trigger it by accessing the same URL.

Before you wrap up, therefore, return to your WordPress root directory and remove the line of code you added earlier. Then save your changes to the file and close it.

3. Restore Your Website Using a Backup Through Your Hosting Provider

If all else fails, you can always use a full backup of your website to restore it to a point when the database was working properly. Ideally, you’ll do this with a recent backup so that you lose as little data as possible.

The problem is that not all WordPress web hosts offer built-in backup functionality for their users. That means you’re often stuck using manual solutions such as plugins. These tools aren’t necessarily bad, but if you don’t have access to your WordPress admin area, restoring a backup becomes a tall order.

Here at Kinsta, on the other hand, you get access to full backups of your website with every plan. To restore your site (including its database) to an earlier point, you just have to access your hosting dashboard and look for the Backups tab:

Restore your backup in MyKinsta

Restore your backup in MyKinsta

Click on the backup you want to restore and you’ll see more details about when it was created. For each backup, there’s a Restore button you can use to return your website to its state at that time.

Do remember, though: using this functionality will overwrite the current version of your website. So you’ll only want to use it as a last-resort measure when you’re sure you won’t lose any critical information.

Experiencing the scary *MySQL Server Has Gone Away* error in WordPress? Don’t sweat it, here are 3 ways to fix it immediately! 😰🔧 #mysql issuesClick to Tweet

Summary

The more your website grows, the more data it will need to store. All of that information goes into your WordPress database. In some cases, if it gets too big, you might run into errors such as “MySQL server has gone away”.

If you encounter this particular error, here are three ways you can get rid of it:

  1. Edit your WordPress wp-db.php file.
  2. Repair your WordPress database.
  3. Restore your website using a backup through your hosting provider.

In this other guide, we show you additional tips and steps on how to repair your WordPress database issues.

Now that you know how to fix, it’s time to actually get rid of this annoying error message. If you’re still experiencing issues with MySQL, you might want to check How to Fix the MySQL 1064 Error.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Понравилась статья? Поделить с друзьями:
  • The error returned was illegal argument to a regular expression
  • The binding of isaac repentance как изменить разрешение
  • The binding of isaac rebirth как изменить управление
  • The error returned was access denied for user
  • The binding of isaac rebirth как изменить разрешение