快轉到主要內容

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

406 字1 分鐘00
作者Y Cheung

💡 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
分享

相關文章

Unity3D接入MySQL数据库

作者 Y Cheung636 字2 分鐘00

系統环境: Windows 10(x64)(version 1909) Unity3D (version 2018.3.0f2) Microsoft Visual Studio …

Aliyun MySQL Aborting

作者 Y Cheung331 字1 分鐘00

放了wordpress的主機最近經常掛掉,提示無法連結數據庫,檢查log信息發現是因為內存不足,把InnoDB的buffer pool size改小後似乎好了一些,可今天還是出錯了 …

忘記 Mysql ROOT 密碼的解決辦法

作者 Y Cheung174 字1 分鐘00

豬腦袋是記不住密碼的。 靠別人也是記不住密碼的。 環境 Ubuntu 操作步驟 修改MySQL配置 在 /etc/my.cnf 中的 [mysqld]段尾處加入以下語句:

↑