To reset the MySQL or MariaDB root password, connect to your server via SSH and first run mysql as the system root user. On Debian and Ubuntu this often logs you in without a password, and one command sets the new one. If not, you start the database briefly without privilege checks, set the password and restart it normally.
Prerequisites
You need an SSH connection to your server as root. How that works is explained in How can I access a Linux server via SSH and transfer data?
Step 1: Check whether you are already logged in
Enter the command mysql. If you don’t get an authentication error, you are already logged in. On Debian and Ubuntu this is often the case, because the system root user may log in via the Unix socket without a password. Set the new password directly and skip steps 2 to 4:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new-password'; Step 2: Start MySQL without privilege tables
To reset the password, MySQL has to run in a mode without privilege checks. Use it only for the duration of the reset, because in this mode anyone can access all databases.
Stop the MySQL server:
systemctl stop mysql Start it without privilege checks and without network access, so nobody can connect from outside in the meantime:
mysqld_safe --skip-grant-tables --skip-networking & The output shows that MySQL is running in this unsafe mode.
Step 3: Reset the password
Open the MySQL console:
mysql Reload the privilege tables first. Only then does ALTER USER work. Then set the new password for root:
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new-password';
quit; The old way via UPDATE mysql.user ... password() no longer works from MySQL 8 and MariaDB 10.4 onwards.
Step 4: Restart MySQL normally
Stop the unsafe instance. Root now has a password, so enter the new one when asked:
mysqladmin -uroot -p shutdown Start the normal MySQL server:
systemctl start mysql Step 5: Test the new password
mysql -uroot -p Enter the new password when prompted. Alternatively test the login in phpMyAdmin. For phpMyAdmin a separate database user is the better choice, see How do I install phpMyAdmin on my server?
Common pitfalls
- „Access denied for user ‚root’@’localhost'“ after the reset: With a password set, the plain
mysqlcommand without-pno longer logs you in. Usemysql -uroot -p. - ALTER USER fails in step 3:
FLUSH PRIVILEGES;is missing. Run it first, then repeat the command. - You want to reach the database from another machine: That needs extra steps, see Make MySQL accessible from outside.