最近遇到一个MySQL连接的问题,远程连接MySQL时遇到“ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0”错误,如下所示:
[root@DB-Server ~]# mysql -h 10.13.65.93 -u onecard -p
Enter password:
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0
这个测试的MySQL位于阿里云Kubernetes(K8s)中Docker容器里面,而且在远程连接MySQL出现上面错误的时候,Docker也会出现下面错误。
一般出现“ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet'”错误的原因较多:
1:网络异常或时延非常高的时候, 超过连接时间限制(系统变量connect_timeout)会导致这个错误。MySQL客户端与数据库建立连接需要发起三次握手协议,正常情况下,这个时间非常短,但是一旦网络异常,网络超时等因素出现,就会导致这个握手协议无法完成,MySQL有个参数connect_timeout,它是MySQL服务端进程mysqld等待连接建立完成的时间,单位为秒。如果超过connect_timeout时间范围内,仍然无法完成协议握手话,MySQL客户端会收到异常。 更多详细信息可以参考我这篇博客“MySQL参数max_connect_errors分析释疑”,但是当前这个案例中,不存在网络延时情况,如下所示:
2:域名解析会导致这个问题。当客户端连接上来,服务器端都会对客户端进来的IP地址进行DNS解析,来获得客户端的域名或主机名,如果DNS解析出了问题或DNS解析相当慢,就会导致连接验证用户出现问题。而skip-name-resolve这个参数的意义就是禁止域名解析。官方文档解释如下:
For each new client connection, the server uses the client IP address to check whether the client host name is in the host cache. If so, the server refuses or continues to process the connection request depending on whether or not the host is blocked. If the host is not in the cache, the server attempts to resolve the host name. First, it resolves the IP address to a host name and resolves that host name back to an IP address. Then it compares the result to the original IP address to ensure that they are the same. The server stores information about the result of this operation in the host cache. If the cache is full, the least recently used entry is discarded.
The server handles entries in the host cache like this:
When the first TCP client connection reaches the server from a given IP address, a new cache entry is created to record the client IP, host name, and client lookup validation flag. Initially, the host name is set to NULL and the flag is false. This entry is also used for subsequent client TCP connections from the same originating IP.
另外,在这个案例的测试过程中,发现skip_name_resolve为OFF的情况下,将connect_timeout设大,也不会出现这个错误
mysql> show variableslike'%connect_timeout%';
+-----------------+-------+
| Variable_name |Value|
+-----------------+-------+
| connect_timeout | 10 |
+-----------------+-------+
1rowinset(0.01 sec)
mysql>setglobalconnect_timeout=30;
Query OK, 0rowsaffected (0.00 sec)