概要
MySQLにアクセスしようとして、今まで問題なかったのに何かのタイミングで以下のエラーが出ることがあります。
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
このエラーは多くの方が経験したことがあると思いますが、以下の流れでうまくいきました。
1. ディレクトリを移動する。
$ cd /usr/local/var
2. ディレクトリの状態を確認する。
$ ls -l
total 0
drwxr-xr-x 3 Masahiro admin 96 5 14 21:27 cache
drwxr-xr-x 4 Masahiro admin 128 4 21 2017 homebrew
drwxr-xr-x 2 Masahiro admin 64 4 29 2017 log
drwxr-xr-x 26 _mysql _mysql 832 11 8 01:39 mysql
drwx------ 23 Masahiro admin 736 2 12 2015 postgres
mysqlの所だけMasahiro
ではなく_mysql
となっています。
3. ディレクトリの権限を変更する。
$ sudo chown -R [ユーザー名] mysql
[ユーザー名]の部分に任意のユーザー名を入れます。
$ sudo chown -R Masahiro mysql
変更を確認します。
$ ls -l
total 0
drwxr-xr-x 3 Masahiro admin 96 5 14 21:27 cache
drwxr-xr-x 4 Masahiro admin 128 4 21 2017 homebrew
drwxr-xr-x 2 Masahiro admin 64 4 29 2017 log
drwxr-xr-x 26 Masahiro _mysql 832 11 8 01:39 mysql
drwx------ 23 Masahiro admin 736 2 12 2015 postgres
先ほど_mysql
だったところがMasahiro
に変更できました。
4. MySQLにアクセスする。
$ mysql -u root -p
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.20 Homebrew
Copyright (c) 2000, 2017, 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>
これでうまくいきました。
調べると同じようなエラーでも他の方法で解決したケースもあるようですが、権限の確認を行うようにすると比較的早く解決するかもしれません。