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

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

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

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

Illuminate\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文件如下:

version: '3'
services:
  mysql:
    image: mysql:latest
    restart: always
    volumes:
      - '~/Documents/Datas/Laravel/mysql:/var/lib/mysql'
    ports:
      - '127.0.0.1:33306:3306'
    environment:
      MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
      MYSQL_DATABASE: 'laravel'
    command: --default-authentication-plugin=mysql_native_password
  laravel:
    image: ycheung/laravel-dev:latest
    restart: always
    ports:
      - '9086:80'
    volumes:
      - '~/Documents/Laravel:/var/www/html'
    depends_on:
      - mysql

Y Cheung

Y Cheung

Blogger, Programer & Traveler.
Shanghai