MYSQL ERROR 2002 (HY000): Can't connect to local MySQL server
错误信息:
出现在使用root用户连接mysql时出现的错误提示:
RROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Mysql.sock文件有什么用
mysql 支持 socket 和 TCP/IP 连接。那么 mysql.sock 这个文件有什么用呢?连接localhost通常通过一个Unix域套接字文件进行,一般是/tmp/mysql.sock。如果套接字文件被删除了,本地客户就不能连接。/tmp 文件夹属于临时文件,随时可能被删除。
TCP 连接(如果报错 /tmp/mysql.sock,你可以尝试这种方式连接)
mysql -uroot -h 127.0.0.1 -p
socket 连接(如果一定要用这种方式连接,你可以以下解决方式)
mysql -uroot -p
解决方式
重启mysql,还是报同样的错
[root@centos7 mysql]# /etc/init.d/mysqld restart
Shutting down MySQL.................... [ 确定 ]
Starting MySQL.............................................[ 确定 ]
[root@centos7 mysql]# mysql -uroot -p
Enter password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
看一下my.cnf
[root@centos7 mysql]# more my.cnf |grep sock
socket=/var/lib/mysql/mysql.sock
socket=/var/lib/mysql/mysql.sock
可以看到我的mysql已经声明了mysql.sock的文件位置,而错误提示为/tmp/mysql.sock; 也就是说虽然我的mysql声明了sock文件的位置,但是客户端在连接的时候, linux系统总是去/tmp目录下去找,找到了原因,就可以对症下药了:
为mysql.sock创建链接文件
[root@centos7 mysql]# ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock
然后再次连接mysql,成功连接
[root@centos7 mysql]# ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock
[root@centos7 mysql]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 8.0.34 MySQL Community Server (GPL)
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
end,至此问题解决