MySQL5.7以前と8.0以上でユーザ認証の方法が変更になりました。MySQL 8.0以降では、ユーザー認証方法が変更されました。この変更により、特にHomebrewを使用してMySQLをインストールした場合に、以下のようなエラーが発生することがあります。
1. PIDファイル更新エラー
「PIDファイルが更新されていない」というエラーが表示され、MySQLサーバーが何らかの理由で正常に起動できない問題
% mysql.server start
Starting MySQL
. ERROR! The server quit without updating PID file (/opt/homebrew/var/mysql/****-MacBook-Air.local.pid).
2. ソケットファイル接続エラー:
「サーバーが正常に起動していないため、ソケットファイルが存在しない」と出る問題
% mysql -u root
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
上記2つが出て認証方法変更に苦労しました。
MySQL認証エラーの解決方法
まずは立ち上がっているmy.confを削除するという方法もありますが、アンインストールが結果的には一番早かったです。
1. MySQLのアンインストールと再インストール:
- 既存のMySQLをアンインストール: brew uninstall mysql@8.0
- 再インストール: brew install mysql@8.0
- サービスの再起動: brew services restart mysql@8.0
2. 認証プラグインの変更:
- /opt/homebrew/etc/my.cnfファイルを編集
- [mysqld]セクションに以下を追加:
default_authentication_plugin=mysql_native_password
MySQLを再起動:
brew services restart mysql@8.0
3.rootユーザーの認証方法変更
- MySQLにログイン: mysql -u root
- 以下のコマンドを実行:
ALTER USER 'root'@'localhost' identified WITH mysql_native_password BY '';
4.変更の確認:
mysql> select User, Plugin from mysql.user;
+------------------+-----------------------+
| User | Plugin |
+------------------+-----------------------+
| mysql.infoschema | caching_sha2_password |
| mysql.session | caching_sha2_password |
| mysql.sys | caching_sha2_password |
| root | mysql_native_password |
+------------------+-----------------------+
4 rows in set (0.00 sec)
これでrootのPluginも「mysql_native_password」に変更されていることを確認できます。