VPS Tutorials
MySQL 2006/2013 on a VPS: Lost Connections, Pools and Packets (2026)
Diagnose disconnects by their timing, check restarts, stale pools, packet limits and deadlines, then verify safe retries and reversible configuration.

The first request after an idle period fails with MySQL server has gone away; a SQL import stops at ERROR 2006; or a long export returns ERROR 2013: Lost connection to MySQL server during query. All indicate a lost database connection, but the failure stage determines the repair.
Record the time, complete error, operation and MySQL logs before deciding between a stale pooled connection, oversized packet, transport/client timeout or server restart. This guide covers self-managed Linux VPS installations of MySQL 8.0/8.4, with examples checked against MySQL 8.4 documentation. MariaDB, managed databases and other drivers require their own parameter/privilege references.
| Timing | First investigation | Verification |
|---|---|---|
| First request after inactivity fails; refresh works | Stale pool session; database/proxy idle timeout | Wait beyond the original interval and test the first application request |
| Import/bulk INSERT fails at a similar point | Statement/BLOB size and both packet limits | Repeat that batch in isolation and verify rows/results |
| Query/export disconnects midway | Driver read timeout, network, result transfer and logs | Complete the same operation through the original application route |
| Several applications disconnect together | Restart, OOM, maintenance or proxy failover | Check uptime and error logs |
| New connection fails mentioning authorization packet | Handshake, network and connect_timeout | Connect from the original client path |
MySQL describes 2006/CR_SERVER_GONE_ERROR as inability to send the request and 2013/CR_SERVER_LOST as failure to receive a complete response. These describe the failure, not its root cause. See client error references. For 1040 Too many connections, use pool/max_connections troubleshooting; more slots cannot repair an already closed session.
Run Bash examples in the VPS shell and SQL in the MySQL client. Replace diagnostic_user with an existing diagnostic account; -p prompts for the password. Reading global state or changing settings requires appropriate privileges.
# 数据库确实监听在本机 TCP 3306 时使用
mysql --protocol=TCP -h 127.0.0.1 -P 3306 -u diagnostic_user -p --skip-reconnect
For Docker, use the correct Compose project; db is an example service:
docker compose exec db mysql -u diagnostic_user -p --skip-reconnect
Keep database ports private. Disabling client automatic reconnect exposes actual failures during diagnosis; this CLI flag does not change the website driver's settings. See mysql client options.
Collect read-only state with timestamps:
SELECT NOW() AS sampled_at, VERSION() AS mysql_version,
@@hostname AS server_host, @@port AS server_port,
CONNECTION_ID() AS diagnostic_connection_id;
SELECT @@GLOBAL.wait_timeout AS global_wait_timeout,
@@SESSION.wait_timeout AS session_wait_timeout,
@@GLOBAL.interactive_timeout AS global_interactive_timeout,
@@GLOBAL.max_allowed_packet AS global_max_allowed_packet,
@@SESSION.max_allowed_packet AS session_max_allowed_packet,
@@SESSION.net_read_timeout AS session_net_read_timeout,
@@SESSION.net_write_timeout AS session_net_write_timeout,
@@GLOBAL.connect_timeout AS global_connect_timeout;
SHOW GLOBAL STATUS
WHERE Variable_name IN
('Uptime', 'Aborted_clients', 'Aborted_connects',
'Threads_connected', 'Threads_running');
SHOW GLOBAL VARIABLES
WHERE Variable_name IN ('log_error', 'log_error_verbosity');
SESSION belongs to this diagnostic session. Applications can initialize different values; inspect their own connections. Aborted_clients and Aborted_connects are cumulative counts for abnormal established-session endings and failed connection establishment respectively. Compare increments; a single total cannot attribute an incident. See communication errors.
When several applications fail together, inspect MySQL first. Convert application, database and kernel timestamps to one timezone. For systemd, the service may instead be mysqld:
sudo systemctl status mysql --no-pager -l
sudo journalctl -u mysql --since '30 minutes ago' --no-pager -n 200
sudo journalctl -k --since '30 minutes ago' --no-pager |
rg -i 'out of memory|oom|killed process'
free -h
df -h
df -i
Without rg, use grep -Ei for equivalent filtering. Read the actual log_error file when journal entries omit database errors.
For Docker, in the project directory:
docker compose ps -a
docker compose logs --since 30m --tail 200 db
db_container_id=$(docker compose ps -a -q db)
if [ -n "$db_container_id" ]; then
docker inspect --format 'Name={{.Name}} RestartCount={{.RestartCount}} State={{json .State}}' "$db_container_id"
docker stats --no-stream "$db_container_id"
fi
This assumes one db container; inspect every replica. Compare exits, restart counts, OOMKilled and startup messages with disconnect times. Current state can obscure the previous exit, so OOMKilled=false does not replace historical kernel logs.
For OOM evidence, assess host/container memory, connections and peak load. Do not increase pools and packet limits together on an undersized host. Restarting immediately loses evidence; deleting data or docker compose down -v is not a disconnect repair. See server has gone away for uptime/log diagnosis.
An application returns a session to its pool; the database/proxy closes it while idle; the next request discovers that only when sending SQL. Check:
wait_timeouton the application's actual session.- Shorter timeouts in proxies, tunnels or network equipment.
- Checkout health checks, invalid-session disposal and lifetime recycling.
wait_timeout controls noninteractive idle waiting; interactive clients can initialize differently. Changing a global value with SET GLOBAL generally does not update existing sessions. See system-variable usage.
For a service already using SQLAlchemy 2.x/PyMySQL, adjust its existing Engine initialization:
import os
from sqlalchemy import create_engine
engine = create_engine(
os.environ["DATABASE_URL"],
pool_pre_ping=True,
pool_recycle=900,
)
Provide the existing mysql+pymysql URL through the environment without logging it. 900 seconds is illustrative: choose below the confirmed expiry interval while considering reconnect cost. Do not create an Engine for each request.
pool_pre_ping checks at checkout; pool_recycle replaces over-age sessions at checkout. Neither protects a connection already held by an active transaction. Avoid sharing established connections across parent/child processes. See SQLAlchemy pooling. Other language pools use different options. After deployment, wait beyond the original interval and test the first request; repeated refreshes immediately after restart miss the condition.
Look for ER_NET_PACKET_TOO_LARGE and the size of a single INSERT, BLOB or string. A 2 GB backup does not require a 2 GB packet allowance; an individual protocol packet, statement or result row matters. Client and server each have limits; see Packet Too Large.
Reduce batches/data per operation first. If measurements establish a need for 128 MiB, record the original and assess memory before this example change:
-- 由有权限的管理员执行;这是运行时修改
SELECT @@GLOBAL.max_allowed_packet AS original_packet_limit;
SET GLOBAL max_allowed_packet = 134217728;
In MySQL 8.4, session max_allowed_packet is read-only; SET SESSION cannot change it. After changing global state, reconnect and inspect new session values, replacing application pool connections gradually. The limit is not an immediate full allocation per connection, but concurrent large transfers increase memory. See max_allowed_packet.
Use a backed-up, isolated restore target and verify results. This illustrates local TCP import only:
mysql --protocol=TCP -h 127.0.0.1 -P 3306 \
-u restore_user -p --skip-reconnect --max-allowed-packet=128M \
restore_test < /srv/backups/restore-test.sql
Replace account/file/database. --max-allowed-packet belongs to the CLI, not necessarily the web driver. Inspect backup USE, CREATE DATABASE and qualified database names to prevent writes to another target. Restrict the restore account accordingly.
Do not blindly rerun a partial import: earlier statements may have committed. Determine completed batches, uniqueness conflicts and replay safety, then recreate the isolated target or resume a confirmed batch. --force does not make a restore successful by skipping errors.
| Setting | Controls | Common misinterpretation |
|---|---|---|
wait_timeout | Idle established session | All query execution time |
connect_timeout | Connection handshake | Long queries after connection |
net_read_timeout | Server waiting for further client data | Every export |
net_write_timeout | Server sending data to the client | Ignoring slow result consumption |
| Driver read/write timeout | Client waiting/sending | Automatically changed by server configuration |
| HTTP/proxy/job timeout | Request/gateway/task deadline | Necessarily a database disconnect |
See server variables. If failures occur after similar durations, compare all deadlines instead of raising them together. A 30-second client deadline with a 45-second query calls for plan/index/task review before extending it. For large results examine pagination, streaming, consumption and network; avoid unlimited production scans.
Only when logs establish upload waiting as the issue, temporarily change that parameter in the same dedicated import session, then restore or close it. 2013 alone is insufficient evidence. Compare the same SQL remotely and locally for remote-only failures, then inspect tunnels/proxies, loss and resets. Local success narrows the investigation; see lost-connection guidance.
Verify runtime changes first. Record original global/application-session values, configuration source, time, scope and results. For an already loaded configuration file, this is illustrative:
[mysqld]
max_allowed_packet=128M
A file edit need not change runtime state. Confirm Docker mounts, startup arguments and retained volumes; container writable-layer edits can disappear. Schedule necessary restarts through maintenance rather than interrupting service for a dynamic variable.
SET PERSIST changes globals and writes mysqld-auto.cnf in the data directory. Coordinate file, argument and persisted sources. Container recreation retains it only with the appropriate directory/loading configuration. See persisted variables.
Rollback restores recorded runtime values and their configuration source. If using SET PERSIST, restore a preexisting persisted value or remove only the newly added override. RESET PERSIST removes persistence without restoring runtime; do not clear all settings. Recheck globals and new application sessions for initialization overrides.
Bounded read retries require business permission. For writes—orders, payments, stock or migrations—a missing success response does not prove no execution/commit.
- Discard the invalid connection and establish a fresh one.
- Check a business ID, idempotency key or audit record for completion.
- If replay is necessary and safe, retry the complete transaction with a bound and backoff.
- Reconcile uncertain outcomes/external effects rather than automatically replaying one statement.
Automatic reconnection does not preserve old transaction state, session variables or temporary objects; see MySQL reconnect effects. Pool health checks cannot eliminate mid-transaction failures; SQLAlchemy requires application handling.
- Stable process: increasing uptime; no correlated restart, OOM or crash.
- Stable pool: first request after the original idle interval succeeds, without endless reconnects.
- Large packets: original batch completes in isolation with row/result checks.
- Long operations: original application/proxy route returns complete results.
- Effective settings: runtime, persisted sources and new-session values agree.
- Capacity: monitor connections, memory and error increments; no new 1040/OOM.
- Safe retries: idempotency/reconciliation prevents duplicate orders, migrations and imports.
One successful SELECT 1 establishes only that attempt. Observe the original failing conditions for at least one former failure cycle.
Restarting refreshes connections or frees resources. Idle expiry, packet problems and OOM can recur; preserve evidence and test that condition.
It may delay idle cleanup but cannot repair proxy/network or active-transaction failures, and retains idle resources longer. Fix connection disposal and capacity first.
No. Network failures, process exits, packets and client deadlines can produce it. Correlate timing/logs before changing SQL or timeouts.
Require each setting's stage, current value, supporting logs, capacity impact and rollback. Timeline collection, pool-initialization review and configuration diffs are useful tasks. Preserve explicit outcome reconciliation before retrying writes/migrations.