Recover MySQL root password - Linux


If you've forgotten the root user's password you created for your MySQL database, you can reset it.

It's important to note that this user and its password are limited to administrator use. This is not the user or password you should use for everyday use.

Turn off MySQL

Warning: If you have any sites or application that rely on MySQL to function, these will stop working until you turn MySQL back on.

You must turn the MySQL service off to reset the root password. The command you use to turn MySQL off varies depending on your Linux distribution. Choose the command from the table below for the Linux version you are using:

Distributions Command
Ubuntu, Debian sudo service mysql stop
Fedora, CentOS, Redhat sudo service mysqld stop
CentOS 7, Redhat 7 sudo systemctl stop mariadb.service
Arch Linux sudo systemctl stop mysqld.service

Reset the root password through safe mode

MySQL safe mode lets you change system settings without using the root password.

  1. Start up safe mode

    sudo mysqld_safe --skip-grant-tables

  2. Log into MySQL as root:

    mysql -u root

  3. Change to the mysql database, which handles the settings for MySQL itself:

    use mysql;

  4. Update the password for the root user:

    update user set password=PASSWORD("the new password you want to use") where User='root';

  5. Refresh the MySQL user privileges:

    flush privileges;

  6. Exit MySQL:

    exit

    Note - If this doesn't work, you can try force the application to quit by pressing CTRL-C on your keyboard.

Stop and Start MySQL

Now that the password has been reset, you need to stop and start the MySQL service.

  1. Stop MySQL. Use the table in the "Turn off MySQL section" to find the command.

  2. Start MySQL:

    Distributions Command
    Ubuntu, Debian sudo service mysql start
    Fedora, CentOS, Redhat sudo service mysqld start
    CentOS 7, Redhat 7 sudo systemctl start mariadb.service
    Arch Linux sudo systemctl start mysqld.service
  3. Connect to MySQL again with your root user:

    mysql -u root -p

  4. Enter your new password.