Lost connection to MySQL server at 'reading initial communication packet', system error: 0
客戶端嘗試建立連接、進行 SSL/TLS 握手或讀取服務端握手包時連接中斷。
vim /etc/my.cnf # 或 /etc/mysql/my.cnf
# 找到並註釋掉
# bind-address = 127.0.0.1
# 或改為 0.0.0.0 監聽所有介面
bind-address = 0.0.0.0
[mysqld]
skip-name-resolve
原理:默認 MySQL 會對連接 IP 執行反向 DNS 解析獲取主機名,用於權限匹配。解析失敗/超時會導致握手階段卡住或斷開。skip-name-resolve 直接跳過解析,權限匹配僅用 IP,極大提升連接穩定性與速度。
systemctl restart mysqld
# 1. 基礎連通
ping 192.168.1.100
# 2. 端口通達
telnet 192.168.1.100 3306
# 或
nc -zv 192.168.1.100 3306
# 3. 防火牆狀態
iptables -L -n | grep 3306
firewall-cmd --list-ports
ufw status
-- 查看用戶宿主
SELECT User, Host, plugin FROM mysql.user WHERE User = 'your_user';
-- 權限授予模板(推薦具體 IP 段)
GRANT ALL PRIVILEGES ON db_name.* TO 'app_user'@'192.168.1.%'
IDENTIFIED BY 'StrongPass#2024';
FLUSH PRIVILEGES;
原則:**最小權限、指定 IP 段、強密碼、避免 % 通配符**。
| 參數 | 建議值 | 說明 |
|---|---|---|
| bind-address | 0.0.0.0 | 監聽所有網卡 |
| skip-name-resolve | ON | 禁用 DNS 反解 |
| max_connections | 3000+ | 防連接數耗盡 |
| wait_timeout | 30-60 | 清理空閒連接 |
| max_allowed_packet | 1G | 防大包斷開 |
若啟用 SSL 但客戶端不支持/證書不匹配:
# 客戶端強制非 SSL
mysql -h host -u user -p --ssl-mode=DISABLED
# 或服務端臨時關閉 SSL(生產不建議)
[mysqld]
require_secure_transport = OFF
?useSSL=false&allowPublicKeyRetrieval=true# 服務端錯誤日誌
tail -f /var/log/mysqld.log
# 抓包分析握手過程
tcpdump -i eth0 -nn -s0 port 3306 -w mysql_handshake.pcap
# Wireshark 打開分析 TCP 三次握手、MySQL 協議握手包
"Lost connection at reading initial communication packet" 90% 由 **bind-address 限制** 或 **DNS 反解超時** 引起。標準修復:**bind-address=0.0.0.0 + skip-name-resolve + 重啟**。輔以網絡通達性驗證、權限精確授予、連接池參數優化、SSL 模式對齊,可徹底消除遠程連接不穩定問題。