My earlier post in this thread was as a result of experiencing issues upgrading to 10.0.2 (was receiving error whilst upgrading in my console).
My approach now has been to remove the snap and fresh install any time I get an error I can’t seem to easily resolve, but it seems that a few hours into syncing the new instance the 2006 error is popping up in my log again. The nextcloud mac app then stops syncing (says server replied — Internal Server Error).
Here’s my log from my nextcloud admin:
Error index Exception: {"Exception":"Doctrine\DBAL\Exception\DriverException","Message":"An exception occurred while executing 'UPDATE `oc_filecache` SET `size` = `size` + ? WHERE (`storage` = ?) AND (`path_hash` IN ('d41d8cd98f00b204e9800998ecf8427e', '3b8779ba05b8f0aed49650f3ff8beb4b', '51ac8400ec84acc670e1691540980c57')) AND (`size` > '-1')' with params [1746995, 1]:nnSQLSTATE[HY000]: General error: 2006 MySQL server has gone away","Code":0,"Trace":"#0 /snap/nextcloud/383/htdocs/3rdparty/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php(116): Doctrine\DBAL\Driver\AbstractMySQLDriver->convertException('An exception oc...', Object(Doctrine\DBAL\Driver\PDOException))n#1 /snap/nextcloud/383/htdocs/3rdparty/doctrine/dbal/lib/Doctrine/DBAL/Connection.php(996): Doctrine\DBAL\DBALException::driverExceptionDuringQuery(Object(Doctrine\DBAL\Driver\PDOMySql\Driver), Object(Doctrine\DBAL\Driver\PDOException), 'UPDATE `oc_file...', Array)n#2 /snap/nextcloud/383/htdocs/lib/private/DB/Connection.php(210): Doctrine\DBAL\Connection->executeUpdate('UPDATE `oc_file...', Array, Array)n#3 /snap/nextcloud/383/htdocs/3rdparty/doctrine/dbal/lib/Doctrine/DBAL/Query/QueryBuilder.php(208): OC\DB\Connection->executeUpdate('UPDATE `oc_file...', Array, Array)n#4 /snap/nextcloud/383/htdocs/lib/private/DB/QueryBuilder/QueryBuilder.php(142): Doctrine\DBAL\Query\QueryBuilder->execute()n#5 /snap/nextcloud/383/htdocs/lib/private/Files/Cache/Propagator.php(100): OC\DB\QueryBuilder\QueryBuilder->execute()n#6 /snap/nextcloud/383/htdocs/lib/private/Files/Cache/HomePropagator.php(49): OC\Files\Cache\Propagator->propagateChange('thumbnails/9690...', 1483478732, 1746995)n#7 /snap/nextcloud/383/htdocs/lib/private/Files/Cache/Updater.php(138): OC\Files\Cache\HomePropagator->propagateChange('thumbnails/9690...', 1483478732, 1746995)n#8 /snap/nextcloud/383/htdocs/lib/private/Files/View.php(315): OC\Files\Cache\Updater->update('thumbnails/9690...', 1483478732)n#9 /snap/nextcloud/383/htdocs/lib/private/Files/View.php(1135): OC\Files\View->writeUpdate(Object(OCA\FilesAccessControl\StorageWrapper), 'thumbnails/9690...')n#10 /snap/nextcloud/383/htdocs/lib/private/Files/View.php(672): OC\Files\View->basicOperation('file_put_conten...', '/thumbnails/969...', Array, '\x89PNG\r\n\x1A\n\x00\x00\x00\rIHD...')n#11 /snap/nextcloud/383/htdocs/lib/private/Preview.php(1220): OC\Files\View->file_put_contents('thumbnails/9690...', '\x89PNG\r\n\x1A\n\x00\x00\x00\rIHD...')n#12 /snap/nextcloud/383/htdocs/lib/private/Preview.php(1162): OC\Preview->storeMaxPreview('thumbnails/9690...')n#13 /snap/nextcloud/383/htdocs/lib/private/Preview.php(777): OC\Preview->generatePreview(9690)n#14 /snap/nextcloud/383/htdocs/lib/private/PreviewManager.php(120): OC\Preview->getPreview()n#15 /snap/nextcloud/383/htdocs/apps/files/lib/Controller/ApiController.php(102): OC\PreviewManager->createPreview('files/Cognitive...', 512, 512, true)n#16 [internal function]: OCA\Files\Controller\ApiController->getThumbnail(512, 512, 'Cognitive Bias....')n#17 /snap/nextcloud/383/htdocs/lib/private/AppFramework/Http/Dispatcher.php(160): call_user_func_array(Array, Array)n#18 /snap/nextcloud/383/htdocs/lib/private/AppFramework/Http/Dispatcher.php(90): OC\AppFramework\Http\Dispatcher->executeController(Object(OCA\Files\Controller\ApiController), 'getThumbnail')n#19 /snap/nextcloud/383/htdocs/lib/private/AppFramework/App.php(111): OC\AppFramework\Http\Dispatcher->dispatch(Object(OCA\Files\Controller\ApiController), 'getThumbnail')n#20 /snap/nextcloud/383/htdocs/lib/private/AppFramework/Routing/RouteActionHandler.php(47): OC\AppFramework\App::main('APIController', 'getThumbnail', Object(OC\AppFramework\DependencyInjection\DIContainer), Array)n#21 [internal function]: OC\AppFramework\Routing\RouteActionHandler->__invoke(Array)n#22 /snap/nextcloud/383/htdocs/lib/private/Route/Router.php(293): call_user_func(Object(OC\AppFramework\Routing\RouteActionHandler), Array)n#23 /snap/nextcloud/383/htdocs/lib/base.php(983): OC\Route\Router->match('/apps/files/api...')n#24 /snap/nextcloud/383/htdocs/index.php(48): OC::handleRequest()n#25 {main}","File":"/snap/nextcloud/383/htdocs/3rdparty/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php","Line":116} 2017-01-03T21:25:32+00:00 adam
Error PHP PDOStatement::execute(): Error reading result set's header at /snap/nextcloud/383/htdocs/3rdparty/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php#91 2017-01-03T21:25:32+00:00 adam
Error PHP PDOStatement::execute(): MySQL server has gone away at /snap/nextcloud/383/htdocs/3rdparty/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php#91 2017-01-03T21:25:32+00:00 adam
Fatal webdav Exception: {"Message":"HTTP/1.1 503 Doctrine\DBAL\Exception\DriverException: An exception occurred while executing 'SELECT `uid`, `displayname` FROM `oc_users` WHERE LOWER(`uid`) = LOWER(?)' with params ["adam"]:nnSQLSTATE[HY000]: General error: 2006 MySQL server has gone away","Exception":"Sabre\DAV\Exception\ServiceUnavailable","Code":0,"Trace":"#0 [internal function]: {closure}(Object(Sabre\HTTP\Request), Object(Sabre\HTTP\Response))n#1 /snap/nextcloud/383/htdocs/3rdparty/sabre/event/lib/EventEmitterTrait.php(105): call_user_func_array(Object(Closure), Array)n#2 /snap/nextcloud/383/htdocs/3rdparty/sabre/dav/lib/DAV/Server.php(446): Sabre\Event\EventEmitter->emit('beforeMethod', Array)n#3 /snap/nextcloud/383/htdocs/3rdparty/sabre/dav/lib/DAV/Server.php(248): Sabre\DAV\Server->invokeMethod(Object(Sabre\HTTP\Request), Object(Sabre\HTTP\Response))n#4 /snap/nextcloud/383/htdocs/remote.php(70): Sabre\DAV\Server->exec()n#5 /snap/nextcloud/383/htdocs/remote.php(168): handleException(Object(Doctrine\DBAL\Exception\DriverException))n#6 {main}","File":"/snap/nextcloud/383/htdocs/remote.php","Line":68,"User":"adam"} 2017-01-03T21:19:56+00:00 adam
Error PHP Error while sending QUERY packet. PID=11238 at /snap/nextcloud/383/htdocs/3rdparty/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php#91 2017-01-03T21:19:56+00:00
This is probably the best I’ve done so far, with only 4 errors in this new snap, and running on 512MB RAM (am running a DreamCompute instance which allows you to upgrade/downgrade RAM easily). Have just stepped it up to 1024MB RAM but have received the same error with the app trying to sync a different file.
Hopefully this is useful for you; let me know if there’s any other info I can provide.
I have encountered this a number of times and I’ve normally found the answer to be a very low default setting of max_allowed_packet
.
Raising it in /etc/my.cnf
(under [mysqld]
) to 8 or 16M usually fixes it. (The default in MySql 5.7 is 4194304
, which is 4MB.)
[mysqld]
max_allowed_packet=16M
Note: Just create the line if it does not exist
Note: This can be set on your server as it’s running.
Note: On Windows you may need to save your my.ini or my.cnf file with ANSI not UTF-8 encoding.
Use set global max_allowed_packet=104857600
. This sets it to 100MB.
answered Feb 28, 2012 at 9:48
GeorgeGeorge
4,8252 gold badges15 silver badges21 bronze badges
15
I had the same problem but changeing max_allowed_packet
in the my.ini/my.cnf
file under [mysqld]
made the trick.
add a line
max_allowed_packet=500M
now restart the MySQL service
once you are done.
answered Oct 17, 2013 at 11:51
Sathish DSathish D
4,83629 silver badges44 bronze badges
3
I used following command in MySQL command-line to restore a MySQL database which size more than 7GB, and it works.
set global max_allowed_packet=268435456;
answered Feb 24, 2016 at 10:31
3
It may be easier to check if the connection exists and re-establish it if needed.
See PHP:mysqli_ping for info on that.
answered Oct 29, 2011 at 23:15
3
There are several causes for this error.
MySQL/MariaDB related:
wait_timeout
— Time in seconds that the server waits for a connection to become active before closing it.interactive_timeout
— Time in seconds that the server waits for an interactive connection.max_allowed_packet
— Maximum size in bytes of a packet or a generated/intermediate string. Set as large as the largest BLOB, in multiples of 1024.
Example of my.cnf:
[mysqld]
# 8 hours
wait_timeout = 28800
# 8 hours
interactive_timeout = 28800
max_allowed_packet = 256M
Server related:
- Your server has full memory — check info about RAM with
free -h
Framework related:
- Check settings of your framework. Django for example use
CONN_MAX_AGE
(see docs)
How to debug it:
- Check values of MySQL/MariaDB variables.
- with sql:
SHOW VARIABLES LIKE '%time%';
- command line:
mysqladmin variables
- with sql:
- Turn on verbosity for errors:
- MariaDB:
log_warnings = 4
- MySQL:
log_error_verbosity = 3
- MariaDB:
- Check docs for more info about the error
answered Feb 21, 2019 at 9:48
jozojozo
3,8221 gold badge24 silver badges29 bronze badges
Error: 2006 (CR_SERVER_GONE_ERROR)
Message: MySQL server has gone away
Generally you can retry connecting and then doing the query again to solve this problem — try like 3-4 times before completely giving up.
I’ll assuming you are using PDO. If so then you would catch the PDO Exception, increment a counter and then try again if the counter is under a threshold.
If you have a query that is causing a timeout you can set this variable by executing:
SET @@GLOBAL.wait_timeout=300;
SET @@LOCAL.wait_timeout=300; -- OR current session only
Where 300 is the number of seconds you think the maximum time the query could take.
Further information on how to deal with Mysql connection issues.
EDIT: Two other settings you may want to also use is net_write_timeout
and net_read_timeout
.
answered Oct 29, 2011 at 23:22
In MAMP (non-pro version) I added
--max_allowed_packet=268435456
to ...MAMPbinstartMysql.sh
Credits and more details here
icedwater
4,6423 gold badges34 silver badges48 bronze badges
answered Feb 29, 2012 at 17:00
uweuwe
3,87011 gold badges36 silver badges49 bronze badges
0
If you are using xampp server :
Go to xampp -> mysql -> bin -> my.ini
Change below parameter :
max_allowed_packet = 500M
innodb_log_file_size = 128M
This helped me a lot
answered Aug 3, 2019 at 8:32
1
I was getting this same error on my DigitalOcean Ubuntu server.
I tried changing the max_allowed_packet and the wait_timeout settings but neither of them fixed it.
It turns out that my server was out of RAM. I added a 1GB swap file and that fixed my problem.
Check your memory with free -h
to see if that’s what’s causing it.
answered Sep 19, 2016 at 23:45
Pikamander2Pikamander2
6,8643 gold badges46 silver badges66 bronze badges
1
On windows those guys using xampp should use this path xampp/mysql/bin/my.ini and change max_allowed_packet(under section[mysqld])to your choice size.
e.g
max_allowed_packet=8M
Again on php.ini(xampp/php/php.ini) change upload_max_filesize the choice size.
e.g
upload_max_filesize=8M
Gave me a headache for sometime till i discovered this. Hope it helps.
answered Oct 16, 2015 at 16:02
3
It was RAM problem for me.
I was having the same problem even on a server with 12 CPU cores and 32 GB RAM. I researched more and tried to free up RAM. Here is the command I used on Ubuntu 14.04 to free up RAM:
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
And, it fixed everything. I have set it under cron to run every hour.
crontab -e
0 * * * * bash /root/ram.sh;
And, you can use this command to check how much free RAM available:
free -h
And, you will get something like this:
total used free shared buffers cached
Mem: 31G 12G 18G 59M 1.9G 973M
-/+ buffers/cache: 9.9G 21G
Swap: 8.0G 368M 7.6G
answered Mar 26, 2017 at 5:38
RehmatRehmat
2,0332 gold badges22 silver badges27 bronze badges
In my case it was low value of open_files_limit
variable, which blocked the access of mysqld to data files.
I checked it with :
mysql> SHOW VARIABLES LIKE 'open%';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| open_files_limit | 1185 |
+------------------+-------+
1 row in set (0.00 sec)
After I changed the variable to big value, our server was alive again :
[mysqld]
open_files_limit = 100000
answered Sep 8, 2016 at 14:31
Fedir RYKHTIKFedir RYKHTIK
9,7446 gold badges56 silver badges67 bronze badges
This generally indicates MySQL server connectivity issues or timeouts.
Can generally be solved by changing wait_timeout and max_allowed_packet in my.cnf or similar.
I would suggest these values:
wait_timeout = 28800
max_allowed_packet = 8M
answered Jun 29, 2018 at 14:35
MemoMemo
1421 gold badge2 silver badges10 bronze badges
If you are using the 64Bit WAMPSERVER, please search for multiple occurrences of max_allowed_packet because WAMP uses the value set under [wampmysqld64] and not the value set under [mysqldump], which for me was the issue, I was updating the wrong one. Set this to something like max_allowed_packet = 64M.
Hopefully this helps other Wampserver-users out there.
answered Mar 14, 2018 at 14:54
Enomatix24Enomatix24
1561 silver badge7 bronze badges
0
There is an easier way if you are using XAMPP.
Open the XAMPP control panel, and click on the config button in mysql section.
Now click on the my.ini and it will open in the editor. Update the max_allowed_packet to your required size.
Then restart the mysql service. Click on stop on the Mysql service click start again. Wait for a few minutes.
Then try to run your Mysql query again. Hope it will work.
answered May 5, 2019 at 5:44
HrijuHriju
7201 gold badge17 silver badges27 bronze badges
It’s always a good idea to check the logs of the Mysql server, for the reason why it went away.
It will tell you.
answered Jun 30, 2018 at 18:06
AlexAlex
31.3k14 gold badges100 silver badges166 bronze badges
MAMP 5.3, you will not find my.cnf and adding them does not work as that max_allowed_packet is stored in variables.
One solution can be:
- Go to http://localhost/phpmyadmin
- Go to SQL tab
- Run SHOW VARIABLES and check the values, if it is small then run with big values
-
Run the following query, it set max_allowed_packet to 7gb:
set global max_allowed_packet=268435456;
For some, you may need to increase the following values as well:
set global wait_timeout = 600;
set innodb_log_file_size =268435456;
answered May 9, 2019 at 20:47
Rupak NepaliRupak Nepali
7191 gold badge6 silver badges13 bronze badges
For Vagrant Box, make sure you allocate enough memory to the box
config.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
end
answered Dec 13, 2015 at 8:39
ShadowebShadoweb
5,5841 gold badge40 silver badges53 bronze badges
0
This might be a problem of your .sql file size.
If you are using xampp. Go to the xampp control panel -> Click MySql config -> Open my.ini.
Increase the packet size.
max_allowed_packet = 2M -> 10M
answered Jan 10, 2018 at 11:43
The unlikely scenario is you have a firewall between the client and the server that forces TCP reset into the connection.
I had that issue, and I found our corporate F5 firewall was configured to terminate inactive sessions that are idle for more than 5 mins.
Once again, this is the unlikely scenario.
answered May 23, 2017 at 18:36
AhmedAhmed
2,7641 gold badge24 silver badges39 bronze badges
uncomment the ligne below in your my.ini/my.cnf
, this will split your large file into smaller portion
# binary logging format - mixed recommended
# binlog_format=mixed
TO
# binary logging format - mixed recommended
binlog_format=mixed
answered Sep 25, 2015 at 14:30
1
I found the solution to «#2006 — MySQL server has gone away» this error.
Solution is just you have to check two files
- config.inc.php
- config.sample.inc.php
Path of these files in windows is
C:wamp64appsphpmyadmin4.6.4
In these two files the value of this:
$cfg['Servers'][$i]['host']must be 'localhost' .
In my case it was:
$cfg['Servers'][$i]['host'] = '127.0.0.1';
change it to:
"$cfg['Servers'][$i]['host']" = 'localhost';
Make sure in both:
- config.inc.php
- config.sample.inc.php files it must be ‘localhost’.
And last set:
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Then restart Wampserver.
To change phpmyadmin user name and password
You can directly change the user name and password of phpmyadmin through config.inc.php file
These two lines
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
Here you can give new user name and password.
After changes save the file and restart WAMP server.
answered Jun 10, 2017 at 8:18
I got Error 2006 message in different MySQL clients software on my Ubuntu desktop. It turned out that my JDBC driver version was too old.
answered Jun 16, 2017 at 15:58
I had the same problem in docker adding below setting in docker-compose.yml
:
db:
image: mysql:8.0
command: --wait_timeout=800 --max_allowed_packet=256M --character-set-server=utf8 --collation-server=utf8_general_ci --default-authentication-plugin=mysql_native_password
volumes:
- ./docker/mysql/data:/var/lib/mysql
- ./docker/mysql/dump:/docker-entrypoint-initdb.d
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
answered Nov 11, 2020 at 17:14
DmitryDmitry
3,7703 gold badges23 silver badges40 bronze badges
1
I also encountered this error. But even with the increased max_allowed_packet
or any increase of value in the my.cnf
, the error still persists.
What I did is I troubleshoot my database:
- I checked the tables where the error persists
- Then I checked each row
- There are rows that are okay to fetch and there are rows where the error only shows up
- It seems that there are value in these rows that is causing this error
- But even by selecting only the primary column, the error still shows up (
SELECT primary_id FROM table
)
The solution that I thought of is to reimport the database. Good thing is I have a backup of this database. But I only dropped the problematic table, then import my backup of this table. That solved my problem.
My takeaway of this problem:
- Always have a backup of your database. Either manually or thru CRON job
- I noticed that there are special characters in the affected rows. So when I recovered the table, I immediately changed the collation of this table from
latin1_swedish_ci
toutf8_general_ci
- My database was working fine before then my system suddenly encountered this problem. Maybe it also has something to do with the upgrade of the MySQL database by our hosting provider. So frequent backup is a must!
answered May 3, 2021 at 1:49
Logan WayneLogan Wayne
5,99116 gold badges32 silver badges48 bronze badges
Just in case this helps anyone:
I got this error when I opened and closed connections in a function which would be called from several parts of the application.
We got too many connections so we thought it might be a good idea to reuse the existing connection or throw it away and make a new one like so:
public static function getConnection($database, $host, $user, $password){
if (!self::$instance) {
return self::newConnection($database, $host, $user, $password);
} elseif ($database . $host . $user != self::$connectionDetails) {
self::$instance->query('KILL CONNECTION_ID()');
self::$instance = null;
return self::newConnection($database, $host, $user, $password);
}
return self::$instance;
}
Well turns out we’ve been a little too thorough with the killing and so the processes doing important things on the old connection could never finish their business.
So we dropped these lines
self::$instance->query('KILL CONNECTION_ID()');
self::$instance = null;
and as the hardware and setup of the machine allows it we increased the number of allowed connections on the server by adding
max_connections = 500
to our configuration file. This fixed our problem for now and we learned something about killing mysql connections.
answered May 20, 2020 at 7:10
MaxMax
2,4811 gold badge22 silver badges27 bronze badges
For users using XAMPP, there are 2 max_allowed_packet parameters in C:xamppmysqlbinmy.ini.
answered Jun 26, 2018 at 12:10
SubhashSubhash
1581 silver badge9 bronze badges
This error happens basically for two reasons.
- You have a too low RAM.
- The database connection is closed when you try to connect.
You can try this code below.
# Simplification to execute an SQL string of getting a data from the database
def get(self, sql_string, sql_vars=(), debug_sql=0):
try:
self.cursor.execute(sql_string, sql_vars)
return self.cursor.fetchall()
except (AttributeError, MySQLdb.OperationalError):
self.__init__()
self.cursor.execute(sql_string, sql_vars)
return self.cursor.fetchall()
It mitigates the error whatever the reason behind it, especially for the second reason.
If it’s caused by low RAM, you either have to raise database connection efficiency from the code, from the database configuration, or simply raise the RAM.
answered Sep 21, 2018 at 10:54
Aminah NurainiAminah Nuraini
17.5k8 gold badges87 silver badges106 bronze badges
For me it helped to fix one’s innodb table’s corrupted index tree. I localized such a table by this command
mysqlcheck -uroot --databases databaseName
result
mysqlcheck: Got error: 2013: Lost connection to MySQL server during query when executing 'CHECK TABLE ...
as followed I was able to see only from the mysqld logs /var/log/mysqld.log which table was causing troubles.
FIL_PAGE_PREV links 2021-08-25T14:05:22.182328Z 2 [ERROR] InnoDB: Corruption of an index tree: table `database`.`tableName` index `PRIMARY`, father ptr page no 1592, child page no 1234'
The mysqlcheck command did not fix it, but helped to unveil it.
Ultimately I fixed it as followed by a regular mysql command from a mysql cli
OPTIMIZE table theCorruptedTableNameMentionedAboveInTheMysqld.log
answered Aug 25, 2021 at 16:04
FantomX1FantomX1
1,4672 gold badges15 silver badges21 bronze badges
-
- #1
Hey there!
For a couple of weeks (and I believe since a minor update, but not sure about it) I have the problem, that my Nextcloud sync doesn’t work properly. I have to users on nextcloud. One with just about 10G of data and another with over 500G of data (mainly photos and music). I use the nextcloud windows client to sync all the data from my OMV server to my local desktop. Since the above mentioned update it stops always at the same file and gives out an error message in the sync client: «[file name and path] — server replied: internal server error». If I look closer in the error logs, it writes «SQLSTATE[HY000]: General error: 2006 MySQL server has gone away». I have googled this and found quite a few «solutions» which I tried out. A lot of changes in my.cnf later I still haven’t found the solution to this problem. I should state, that the 10G of data gets synced fine (even while the sync client shows the error for the 500G-account). Has anyone experienced similar things? Please ask me to show any configuration or error log files you need to help me find a solution.
Thank you!
Alex(During one of my problem solving trials I killed my former SLC-USB-stick where OMV was installed. OMV wouldn’t boot anymore. I have now bought a SSD of similar size and to my surprise, after cloning it with CloneZilla, the SSD booted OMV without problems! Only the above error is still there. Maybe this is important to know. Is my database possibly corrupted because it was on a slowly dying USB-stick? Is there anything I can do to repair it?)
-
- #2
No one has a solution for this problem or an idea, what I could do next?
-
- Offizieller Beitrag
- #3
OMV wouldn’t boot anymore. I have now bought a SSD of similar size and to my surprise, after cloning it with CloneZilla, the SSD booted OMV without problems! Only the above error is still there. Maybe this is important to know. Is my database possibly corrupted because it was on a slowly dying USB-stick? Is there anything I can do to repair it?
When you use clonezilla to clone a bad usb stick to a new stick, you copy the corrupt data to the new one. I recommend wipe the new stick and re-installing. There is no good way to find the corruption unless you have a good backup of the old stick.
-
- #4
Thank you ryecoaaron!!
This was exactly the kind of idea I had needed! I threw away my obviously corrupted databases using the DROP-command from here: https://docs.nextcloud.com/ser…/maintenance/restore.html
After that I reinstalled the configuration of Nextcloud by deleting [pathtoNextcloud]/config/config.php and opening my Nextcloud-instance.I recreated all users and did a file-scan with «sudo -u www-data php occ files:scan [username]» for each user. Doing it for all users with «scan-all» would have worked too, I guess, but I wanted to start with the username, which had the least amount of files…
And now I have a working database again. I tried so hard finding the right configuration settings in my.cnf and all along it was the corrupt database. Which is weird, since it still synced some files…
Thanks again!
Эта ошибка означает, что 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 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 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 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_timeout, net_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