Locked out of MySQL with ERROR 1045 (28000): Access denied for user 'root'@'localhost'?
When root credentials are lost or desynchronized, you cannot change the password while the daemon enforces standard privileges. You must restart the database daemon in a bypass mode, update the authentication tables, and restart the service normally.
Here are two reliable methods to recover access.
Method 1: Using --skip-grant-tables
This method starts the daemon without reading the grant tables, allowing local root login without a password.
-
Stop the running MySQL/MariaDB service:
sudo service mysqld stop # On systemd systems: # sudo systemctl stop mysqld -
Start MySQL safely without grant tables:
sudo mysqld_safe --skip-grant-tables & -
Log into MySQL without credentials:
mysql -u root -
Update the root user password:
USE mysql; UPDATE user SET password = PASSWORD("YOUR_NEW_PASSWORD") WHERE User = 'root'; FLUSH PRIVILEGES; QUIT;(Note: On modern MySQL 5.7+ / 8.0+, use
ALTER USER 'root'@'localhost' IDENTIFIED BY 'YOUR_NEW_PASSWORD';or updateauthentication_string). -
Stop the temporary daemon and restart normally:
sudo killall mysqld sudo service mysqld start
Method 2: Using an --init-file
If you prefer an automated single-pass reset without interactive shells:
-
Create an initialization SQL script (e.g.,
/tmp/reset_pwd.txt):UPDATE mysql.user SET Password = PASSWORD('YOUR_NEW_PASSWORD') WHERE User = 'root'; FLUSH PRIVILEGES; -
Stop the database service:
sudo service mysqld stop -
Execute the init file with
mysqld_safe:sudo mysqld_safe --init-file=/tmp/reset_pwd.txt & -
Stop the instance and restart cleanly:
sudo killall mysqld rm -f /tmp/reset_pwd.txt sudo service mysqld start