解決Laravel連接MySQL8驗證失敗錯誤

Posted by Y Cheung on Thu, Oct 15, 2020

💡 2023-06-14 update

MySQL升級至8.4後這篇文章的方法就失效咯,請移步《解決 MySQL 升級 8.4 Docker 容器啟動問題》查看最新解決方案。

之前一直用MariaDB沒感覺,這次因為需求變動改用最新的MySQL 8 後, Laravel 就無法連接上資料庫了,囧。

對資料庫進行任何操作都出現了 The server requested authentication method unknown to the client 錯誤:

1Illuminate\Database\QueryException  : SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client (SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations)

查了一下,原來是 MySQL 8.0 後預設儲存密碼的方式由原來的 mysql_native_password 改為 caching_sha2_password 了,而 Y Cheung 目前使用的PHP版本7.3 是不支持caching_sha2_password plugin的,據說php7.4開始支持caching_sha2_password了

解決方案:

  • Plan A: 升級PHP版本到7.4
  • Plan B: 降級MySQL版本
  • Plan C: 啟動MySQL Docker的時候使用命令 --default-authentication-plugin=mysql_native_password

完整 Laravel docker-compose.yml文件如下:

 1version: '3'
 2services:
 3  mysql:
 4    image: mysql:latest
 5    restart: always
 6    volumes:
 7      - '~/Documents/Datas/Laravel/mysql:/var/lib/mysql'
 8    ports:
 9      - '127.0.0.1:33306:3306'
10    environment:
11      MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
12      MYSQL_DATABASE: 'laravel'
13    command: --default-authentication-plugin=mysql_native_password
14  laravel:
15    image: ycheung/laravel-dev:latest
16    restart: always
17    ports:
18      - '9086:80'
19    volumes:
20      - '~/Documents/Laravel:/var/www/html'
21    depends_on:
22      - mysql