忘記 MySQL root 密碼是常見運維場景。本文提供 Linux、Windows、Docker 容器三大環境、MySQL 5.7/8.0 版本的完整重置流程,含 skip-grant-tables、init-file、mysqladmin 多種方式,並解決 MySQL 8.0 caching_sha2_password 認證插件導致的舊客戶端連接問題。
繞過權限驗證啟動 MySQL (--skip-grant-tables) → 免密登入 → 更新 mysql.user 表密碼欄位 → 刷新權限 → 正常啟動驗證。
# 1. 停止服務
systemctl stop mysqld
# 或: service mysql stop
# 2. 創建臨時配置目錄與文件
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
# 3. 啟動跳過權限表
mysqld_safe --skip-grant-tables --skip-networking --user=mysql &
# --skip-networking 防止外部連入,安全
# 4. 免密登入
mysql -u root
# 5. 更新密碼 (MySQL 5.7 / 8.0 通用)
USE mysql;
-- MySQL 8.0: authentication_string 欄位
UPDATE user SET authentication_string = NULL WHERE User = 'root';
-- 設置新密碼 (需先 flush privileges 再 alter user)
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass#2024';
-- 或指定舊插件兼容
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'NewStrongPass#2024';
FLUSH PRIVILEGES;
QUIT;
# 1. 創建初始化 SQL 文件
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass#2024';" > /tmp/init_root.sql
# 2. 停止服務
systemctl stop mysqld
# 3. 啟動載入 init-file
mysqld --init-file=/tmp/init_root.sql --user=mysql --daemonize
# 4. 驗證
mysql -u root -pNewStrongPass#2024 -e "SELECT 1;"
mysqladmin -u root -p'old_pass' password 'NewStrongPass#2024'
my.ini (通常在 C:\ProgramData\MySQL\MySQL Server X.Y\my.ini)[mysqld] 下添加:skip-grant-tablesnet stop mysql && net start mysqlmysql -u rootmy.ini 中的 skip-grant-tables,重啟服務。REM 1. 建立 init.sql
echo ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass#2024'; > C:\temp\init_root.sql
REM 2. 停止服務
net stop mysql
REM 3. 手動啟動載入 init-file (需管理員權限)
"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe" --init-file=C:\temp\init_root.sql --console
REM 4. 新終端驗證
mysql -u root -pNewStrongPass#2024 -e "SELECT 1;"
# 1. 進入容器
docker exec -it mysql_container bash
# 2. 容器內執行 Linux 方法 1 或 2
# 或提交新映像包含 init-file (生產不推薦)
# 3. 更簡單:環境變數重建 (僅適用 MYSQL_RANDOM_ROOT_PASSWORD 或首次初始化)
# docker run -e MYSQL_ROOT_PASSWORD=NewPass ... (需刪除卷重建,數據會丟失!)
⚠️ **生產容器請用方法 1/2 保留數據卷**。
MySQL 8.0 預設認證插件為 caching_sha2_password,舊版驅動 (JDBC 5.x、PHP mysqlnd 舊版、舊 Navicat) 不支援。
-- 重置時指定舊插件,兼容所有客戶端
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'NewStrongPass#2024';
FLUSH PRIVILEGES;
mysql -u root -pNewStrongPass#2024 -e "SELECT VERSION();"'root'@'%', 'root'@'127.0.0.1') 需同步修改。/tmp/init_root.sql 等)。忘記 root 密碼**不可怕,標準流程 5 分鐘搞定**。核心:**Linux 用 --init-file 單次重啟最乾淨;Windows 改 my.ini 加 skip-grant-tables 最直觀;MySQL 8.0 必須處理 caching_sha2_password 兼容性**。重置後務必驗證、同步所有 root Host、更新應用配置、記錄審計日誌。