背景


最近发现每天的数据库还原并没有执行了,检查了脚本和备份文件以及定时任务一切正常,于是决定手动执行还原数据库脚本试试:

1
2
[root@centos7 document]# ./mysqlsource.sh
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysqld/mysqld.sock'

果不其然,问题出现在在了脚本上,发现使用mysql -uroot -p就已经无法连接至本机数据库了,却可以通过mysql -h 127.0.0.1 -uroot -p进行数据库连接,这个问题很奇怪。

解决


首先检查下/etc/my.cnf即mysql的配置文件:

1
2
3
4
5
6
[root@centos7 document]# vim /etc/my.cnf
[mysqld]
#federated
datadir=/data/mysql
socket=/data/mysql/mysql.sock
...

可见mysql配置文件中datadirsocket的路径都已经认为调整到了新的目录下,但是为什么报错提示中仍然是/var/lib/mysqld/mysqld.sock呢?问题应该出现在这个地方。

经过几番找寻,发现用rpm安装的话,mysql客户端sock默认是去读取/var/lib/mysql/mysql.sock,如需调整位置,需在/etc/my.cnf文件中手动添加新的socket配置:

1
2
[client]
socket=/data/mysql/mysql.sock

添加完配置再重新启动mysql,就可以正常登录了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[root@centos7 mysql]# service mysqld restart
停止 mysqld: [确定]
正在启动 mysqld: [确定]
[root@centos7 mysql]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 90
Server version: 5.1.73-log Source distribution

Copyright (c) 2000, 2013, 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>