Leif160519的blog Leif160519的blog

——————

目录
MySQL远程连接丢失问题解决方法Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0
/  

MySQL远程连接丢失问题解决方法Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0

最近远程连接mysql总是提示

Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0

很明显这是连接初始化阶段就丢失了连接的错误

其实问题很简单,都是MySQL的配置文件默认没有为远程连接配置好,只需要更改下MySQL的配置文件即可。
具体的解决步骤如下:
找到并修改my.cnf文件。在不同的Linux系统下,my.cnf放在不同的位置。这里以Ubuntu Server做示例,其他系统请根据情况自行找到my.cnf的路径。一般只会存放在/etc/my.cnf或者/etc/mysql/my.cnf下。
首先用vim打开my.cnf:

vim /etc/mysql/my.cnf

看看是否有绑定本地回环地址的配置,如果有,注释掉下面这段文字:(在文字之前加上#号即可)

bind-address = 127.0.0.1

或者改为:

bind-address = 0.0.0.0

然后找到[mysqld]部分的参数,在配置后面建立一个新行,添加下面这个参数(禁用mysql对连接的客户端进行DNS反向解析):

skip-name-resolve

保存文件并重启MySQL:

systemctl restart mysqld

所谓反向解析是这样的:
mysql接收到连接请求后,获得的是客户端的ip,为了更好的匹配mysql.user里的权限记录(某些是用hostname定义的)。
如果mysql服务器设置了dns服务器,并且客户端ip在dns上并没有相应的hostname,那么这个过程很慢,导致连接等待。

添加skip-name-resolve以后就跳过着一个过程了。

官方的解释:
How MySQL uses DNS When a new thread connects to mysqld, mysqld will spawn a new thread to handle the request. This thread will first check if the hostname is in the hostname cache. If not the thread will call gethostbyaddr_r() and gethostbyname_r() to resolve the hostname. If the operating system doesn’t support the above thread-safe calls, the thread will lock a mutex and call gethostbyaddr() and gethostbyname() instead. Note that in this case no other thread can resolve other hostnames that is not in the hostname cache until the first thread is ready. You can disable DNS host lookup by starting mysqld with –skip-name-resolve. In this case you can however only use IP names in the MySQL privilege tables. If you have a very slow DNS and many hosts, you can get more performance by either disabling DNS lookop with –skip-name-resolve or by increasing the HOST_CACHE_SIZE define (default: 128) and recompile mysqld. You can disable the hostname cache with –skip-host-cache. You can clear the hostname cache with FLUSH HOSTS or mysqladmin flush-hosts. If you don’t want to allow connections over TCP/IP, you can do this by starting mysqld with –skip-networking.

根据文档说明,如果你的mysql主机查询DNS很慢或是有很多客户端主机时会导致连接很慢,由于我们的开发机器是不能够连接外网的,所以DNS解析是不可能完成的,从而也就明白了为什么连接那么慢了。同时,请注意在增加该配置参数后,mysql的授权表中的host字段就不能够使用域名而只能够使用 ip地址了,因为这是禁止了域名解析的结果。

参考:


“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill

标  题MySQL远程连接丢失问题解决方法Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0
作  者Leif160519
出  处https://github.icu/articles/2020/05/18/1589781953754.html
关于博主:坐标南京,运维工程师,如有问题探讨可以直接下方留言。
声援博主:如果您觉得文章对您有帮助,可以评论、订阅、收藏。您的鼓励是博主的最大动力!