Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Fix the MySQL Server Has Gone Away Error (ERROR 2006)

A practical, evidence-first guide to MySQL ERROR 2006: identify whether an idle timeout, oversized packet, client setting, lifecycle bug, network failure, or crash broke the connection, then apply the matching fix.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

ERROR 2006 (HY000): MySQL server has gone away means your client tried to use a MySQL connection that was no longer usable. The usual cause is an idle connection closed by the server, but oversized packets, client timeouts, broken connection-lifecycle code, network failures, killed threads, and a server crash can produce the same message. Identify when the failure occurs and collect evidence first; then change the timeout, packet limit, application code, or network configuration that actually matches the cause.

What the error actually means

MySQL documents two closely related client conditions. CR_SERVER_GONE_ERROR means the client could not send a question to the server. CR_SERVER_LOST means the client sent the request but did not receive a complete response. A connector may surface the second condition as Lost connection to MySQL server during query, commonly associated with error 2013. Both messages describe a connection failure, not one single underlying fault.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The important distinction is whether the session was idle, failed while sending a request, failed while waiting for a response, or disappeared because the server or network stopped responding. A retry can hide the symptom temporarily, but it cannot repair a blocked port, an invalid connection shared across forked processes, or a server that is crashing on a particular statement.

Use the timing to narrow the cause

Observed timing or scope Most likely categories First evidence to collect
The first query after a long idle period fails; a new connection works wait_timeout, interactive_timeout, or a stale pool entry Idle duration, session timeout values, and pool validation behavior
A large import, multi-row write, or BLOB operation fails while smaller requests succeed max_allowed_packet, batch size, or a client packet limit Statement or payload size and server and client packet settings
The error occurs after a connector read or write timeout Client-side timeout or disabled/incorrect reconnect handling Connector timeout settings and the exact operation being retried
Only one application host or network path is affected DNS, firewall, routing, TCP configuration, or host-specific access Hostname resolution, port 3306 reachability, and MySQL host-cache data
It follows a process fork or an explicit close A child or later query is using a connection it does not own Connection creation and close points in the application lifecycle
The server uptime reset or a repeatable statement makes mysqld disappear Server restart, killed thread, or crash Error log, uptime, and the statement that preceded the failure

A diagnostic sequence that avoids guesswork

1. Capture the complete failure context

Record the exact error number and text, connector and version, database host, port or socket, query or operation, payload size, and whether the connection had been idle. Note whether a fresh connection succeeds immediately. “It happens sometimes” is not enough to distinguish an eight-hour idle close from a network flap during a write.

Also record the application process model. A connection borrowed from a pool, inherited by a forked child, or stored in a global object has different failure modes from a connection opened and closed inside one request.

2. Check uptime and the error log

Run mysqladmin version (or inspect the server’s uptime status) when the server is reachable. A recent uptime value compared with the incident time can reveal a restart. Review the MySQL error log around the failure for shutdown, crash, or connection-disconnect messages. If the existing detail is insufficient, temporarily increase error-log detail:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
SET GLOBAL log_error_verbosity = 3;

Restore your normal logging policy after diagnosis if the additional volume is not needed. The general query log can help correlate a request with a disconnect, but enable it only for a controlled interval because it records every query and can add substantial I/O and storage overhead.

3. Inspect connection counters and the host cache

These status values show whether disconnects or failed handshakes are increasing:

SHOW GLOBAL STATUS LIKE 'Aborted_clients';
SHOW GLOBAL STATUS LIKE 'Aborted_connects';
SHOW GLOBAL STATUS LIKE 'Connection_errors%';

If Performance Schema is enabled, inspect the host cache for per-host name-resolution and connection errors:

SELECT * FROM performance_schema.host_cacheG

A rise in Aborted_clients is consistent with clients that vanish or fail to close normally, while Connection_errors_* counters can point toward handshake, network, or host-specific problems. These counters do not identify the cause by themselves; compare their changes with the incident timestamps and affected hosts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

4. Read the timeout and packet settings on both sides

Check the values that govern idle sessions and request size:

SHOW GLOBAL VARIABLES WHERE Variable_name IN
('wait_timeout','interactive_timeout','max_allowed_packet');
SHOW SESSION VARIABLES WHERE Variable_name IN
('wait_timeout','interactive_timeout','max_allowed_packet');

The global value is not always the value already assigned to an existing session. A pool can therefore contain connections with older settings even after a global change. Check the connector or command-line client’s packet limit and read/write timeouts separately; a server-side value cannot override a client that gives up first.

5. Test the network path from an affected host

Compare a failing machine with one that works. Verify DNS resolution, routing, firewall rules, and TCP access to port 3306. For example, use your operating system’s resolver and TCP tools, then test a new MySQL connection:

getent hosts db.example
nc -vz db.example 3306
mysqladmin ping -h db.example -P 3306 -u app_user -p

Use equivalent tools where getent or nc are unavailable. If TCP is intentionally disabled with skip_networking, a TCP test will fail even though a local Unix-socket connection may work. A failure limited to one source host warrants checks of DNS, firewall and routing, as well as MySQL host-based privileges.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

6. Reproduce with a small, controlled test

Try a trivial query on a new connection, then repeat the original operation with a smaller payload or shorter idle interval. If only the long-idle test fails, investigate timeout and pool behavior. If only the large request fails, investigate packet limits and batching. If the same statement repeatedly causes the server to restart or become unreachable, stop increasing retries and treat it as a server-crash investigation.

Fix connections closed after inactivity

MySQL says the most common reason for this error is that the server timed out and closed an idle connection. The MySQL 8.0 Reference Manual documents an eight-hour default idle-close period when nothing has happened. The relevant server variable is wait_timeout; interactive clients can also be governed by interactive_timeout. The default is version- and configuration-dependent, so verify the deployed version rather than assuming every server uses eight hours.

Choose a timeout policy based on workload

For a web application, set the pool’s maximum connection lifetime or idle lifetime below the server’s idle timeout, and validate a connection before handing it to a request. For a reporting or batch process that legitimately waits for long periods, either keep the session active intentionally or set a justified server timeout. Raising the timeout indefinitely consumes a connection slot and associated server resources for every idle session.

Where the connector supports it, mysql_ping() (or its language-specific equivalent) can test a borrowed session. If the ping fails, discard the session and establish a new one before issuing work. A reconnect must also restore required session state such as the selected database, character set, time zone, isolation level, temporary tables, and prepared statements.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Change server values deliberately

A configuration-file example is:

[mysqld]
wait_timeout=1800
interactive_timeout=1800

Use values that match measured request and job durations, not an arbitrary large number. A dynamic change such as SET GLOBAL wait_timeout = 1800; affects new sessions; existing pooled sessions may retain their current session value and should be recycled. Make a persistent configuration change through your normal deployment process and restart only when your operational policy requires it.

Make retries safe

Automatic reconnect can turn a connection failure into a silent new session. Never blindly replay a write whose commit status is unknown: the server may have applied it before the network failed. Use transactions, idempotency keys, duplicate-safe statements, or an application-level reconciliation step before retrying writes. Read-only, idempotent operations are easier to retry, but they still need a fresh, correctly initialized session.

Fix oversized requests and packet failures

A query or result that exceeds a packet limit can cause the server to close the connection. MySQL’s documented 8.0 page lists a 64 MB default for max_allowed_packet in that context and notes that the client limit may also need to increase. Treat that figure as a documented default for the cited version, not a universal value for every release or distribution.

Measure the request that fails

Large multi-row INSERT or REPLACE statements are sent as one request. A single BLOB, generated statement, or serialized document can cross the limit even when each row looks small. Capture the approximate encoded request size, not just the number of rows, because character encoding and escaping change the number of bytes on the wire.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Raise both limits only as far as required

Inspect and, if justified, increase the server and client settings:

SHOW GLOBAL VARIABLES LIKE 'max_allowed_packet';

A server configuration might contain:

[mysqld]
max_allowed_packet=128M

Set the matching client or connector option in its own configuration; for the classic command-line client, that option is commonly supplied as --max_allowed_packet=128M or under a [client] section. Reconnect clients after changing a setting so they actually use the new session limit. Confirm the syntax and dynamic-change behavior for your deployed MySQL version before applying it.

Higher packet limits allow larger allocations and can increase memory pressure when many sessions operate concurrently. Set the smallest value that accommodates the largest legitimate request, monitor memory, and roll back if the workload does not require the increase.

Prefer smaller batches when possible

Splitting an import into smaller statements reduces the size of each request and makes failures easier to resume. Keep transactions at a size your storage engine and recovery process can handle. For very large BLOBs, use the connector’s streaming or parameterized-upload facility instead of constructing one enormous SQL string. If reducing the batch still produces a failure with modest payloads, investigate malformed packet ordering, connector bugs, or a network interruption rather than continuing to raise the limit.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fix client-side timeout and reconnect behavior

Connectors commonly expose separate read and write timeouts. A client can terminate an operation while the server is still working, producing a lost-connection message even when MySQL itself is healthy. Compare the timeout with the slowest legitimate query, upload, or network path, then increase it only for operations that need the extra time. A timeout that is too short creates false failures; one that is too long delays detection of a genuinely dead server.

Understand whether automatic reconnect is enabled. With reconnect disabled, a server-side idle close remains visible to the application, which is safer because the code can reinitialize session state. With reconnect enabled, a connector may silently create a new session and lose temporary tables, variables, prepared statements, or transaction context. Implement an explicit “validate, reconnect, reinitialize” path and make write retries conditional on knowing whether the prior attempt committed.

Repair connection-lifecycle mistakes

Do not use a connection after closing it

Calling a close or disconnect method and then issuing another query is an application logic error. Make ownership clear: the component that acquires a pooled connection should release it, and code should not retain a reference after release. Add connection-state checks in development and log the acquisition, release, and failure path when diagnosing intermittent errors.

Open one connection per forked child

A process created with fork() inherits the parent’s file descriptors, but the inherited MySQL connection is not a safe shared channel. Close inherited database handles in the child and create a separate connection after the fork. Do this for every worker process, and do not let two processes write to the same protocol stream.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Likewise, configure a thread-safe pool according to the connector’s rules rather than sharing one connection object across independent execution contexts. A connection that appears healthy in one worker can be consumed or closed by another, leading to apparently random 2006 or 2013 errors.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Repair DNS, firewall, and TCP failures

Database settings cannot fix a blocked port or a broken network link. Check that the hostname resolves to the intended address from the application host, that firewalls permit the MySQL port, and that routing and TCP configuration are consistent on both ends. Inspect network equipment when failures correlate with a particular path, interface, or address family.

If local socket connections work but TCP connections fail, review skip_networking, the bind address, firewall policy, and name resolution. If only one hostname or source address fails, compare its DNS result and host-based MySQL privileges with a working host. Correct the underlying network or access issue rather than increasing wait_timeout or enabling aggressive reconnects.

Investigate killed threads, restarts, and crashes

An administrator can kill a thread, and a server crash can terminate every active connection. Check the error log and uptime at the incident time, then identify the statement or administrative action immediately before the disconnect. A repeatable query that makes mysqld restart or vanish requires a crash investigation, resource review, and possibly a version-specific bug fix; retries merely repeat the trigger.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use mysqladmin version or the server uptime status to distinguish a long-lived server from one that restarted during the incident. Preserve the relevant error-log entries, query text, schema conditions, and payload characteristics for whoever administers the server. If a thread was intentionally killed, determine why and change the job, resource limit, or administrative procedure that caused the termination.

Apply configuration changes safely

  • Record the current global and session values before changing anything.
  • Change one category at a time: timeout, packet size, connector behavior, or network configuration.
  • Recycle existing pool connections after changes that affect session initialization.
  • Stage larger packet limits or longer timeouts on a representative workload and watch memory, connection counts, latency, and error counters.
  • Persist successful settings through managed configuration rather than relying on a one-time dynamic command.
  • Keep a rollback value and a timestamped incident log so a later failure can be compared with the previous baseline.

Practical fixes by common scenario

“It fails only on Monday morning”

Measure the weekend idle interval and compare it with the session’s wait_timeout. Configure pool validation and a maximum lifetime below that threshold, then ensure a newly opened connection receives the same session initialization as the old one.

“A CSV import fails, but small inserts work”

Estimate the largest encoded statement, inspect both packet limits, and reduce rows per statement before raising limits. If the payload genuinely requires more capacity, increase server and client values together and account for concurrent memory use.

“Only one worker reports the error after multiprocessing starts”

Audit where the connection was opened relative to fork(). Give each child its own connection and prevent the parent connection object from being reused in children.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“The error appears only from one application host”

Compare DNS answers, port 3306 reachability, firewall and routing rules, and host-cache counters with a working host. A database timeout change is not a remedy for a host-specific network path.

“The same report takes down the server”

Stop automatic retries, preserve the exact query and parameters, check uptime and the error log, and treat the event as a server crash or administrative termination. Resolve that underlying failure before tuning client reconnects.

Prevent the error from returning

  • Set pool idle and maximum lifetimes from measured workload limits, with validation before checkout.
  • Instrument query duration, payload size, reconnects, and error codes 2006 and 2013 separately.
  • Keep import batches bounded and test the largest BLOB or row set used in production.
  • Create database connections after process forks and make ownership explicit.
  • Monitor Aborted_clients, Aborted_connects, Connection_errors_*, host-cache errors, uptime, and memory.
  • Document the connector’s read, write, and reconnect settings alongside server configuration.
  • Test DNS, firewall, and failover paths from every production application network.

Once timing, logs, counters, packet sizes, and connection ownership agree on a cause, the fix is usually narrow: recycle stale sessions, resize or split a request, repair lifecycle code, correct the network, or investigate the server failure. Changing unrelated MySQL variables without that evidence risks adding resource pressure while leaving the real fault in place.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.