我在Debian Wheezy(apt-get install mysql-server mysql-client
)上有一个非常标准的MySQL安装,我已经成功完成了很多次。
当我尝试通过连接时localhost
,一切正常。但是通过连接127.0.0.1
会出现错误消息:
$ mysql -h localhost -P 3306 -u xxx -p
-- works
$ mysql -h 127.0.0.1 -P 3306 -u xxx -p
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0
当我尝试从Java应用程序进行连接时,尽管我将其localhost
用作主机名,但也会遇到类似的错误:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure. The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
当MySQL服务器关闭空闲连接或重新启动时,通常会出现此异常。但是,当应用程序首次尝试连接时,这会在应用程序启动时发生。
有趣的是,这确实在几个小时前就起作用了。不幸的是,我不记得更改了服务器上的任何内容。:-(
因此,老实说,这篇文章包含两个问题:为什么我不能通过连接127.0.0.1
?为什么localhost
我可以通过CLI来连接我的应用程序?
# mysqld -V
mysqld Ver 5.5.37-0+wheezy1-log for debian-linux-gnu on x86_64 ((Debian))
# mysql -V
mysql Ver 14.14 Distrib 5.5.37, for debian-linux-gnu (x86_64) using readline 6.2
# grep bind /etc/mysql/my.cnf
bind-address = 127.0.0.1
# grep socket /etc/mysql/my.cnf
socket = /var/run/mysqld/mysqld.sock
# ping localhost
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.022 ms
# grep localhost /etc/hosts
127.0.0.1 localhost
::1 ip6-localhost ip6-loopback
# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT tcp -- anywhere anywhere tcp
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
# netstat -ln | grep 3306
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
tomcat # grep mysql conf/server.xml
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dbname"
编辑
我尝试将服务器绑定到0.0.0.0
和::
,但无济于事。
该服务器支持IPv6,并进行了相应配置:
# host localhost
localhost has address 127.0.0.1
localhost has IPv6 address ::1
当我尝试连接到时,会发生与上述相同的问题::1
。
# ping6 ::1
64 bytes from ::1: icmp_seq=1 ttl=64 time=0.020 ms
# ping6 localhost
64 bytes from ip6-localhost: icmp_seq=1 ttl=64 time=0.018 ms
编辑2
通过进行连接telnet
不会提供很多信息,但是表明该连接会立即关闭。
# telnet localhost 3306
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
顺便说一句,即使启用了日志记录,MySQL日志文件也是完全安静的。
localhost
到套接字,而是使用网络。正如人们自然期望的那样...但是最初的问题仍然存在。