How to change mysql root password on Linux

If you’ve forgotten the MySQL password for the root user, we’ve got you covered in this guide. Follow our step by step instructions to reset the root password on a Linux system via the command line.

In this tutorial you will learn:

  • How to change/reset MySQL root password

Reset MySQL root password

Reset MySQL root password

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software MySQL
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

How to change/reset MySQL root password



Step by step instructions:

  1. Start off by stopping the MySQL service with a systemctl command:
    $ sudo systemctl stop mysql
    
  2. Now, we need to restart the MySQL service but without password privileges being granted. Note that the & at the end of the command just runs the service in the background and will allow us to continue using the current terminal.
    $ sudo mysqld_safe --skip-grant-tables &
    
  3. You’ll now be able to connect to the MySQL server as root, without specifying a password:
    $ mysql -u root
    
  4. Now, reset the root password, but first flush the privileges to reload the grants:
    mysql> FLUSH PRIVILEGES;
    mysql> use mysql;
    mysql> update user set plugin="mysql_native_password" where User='root';
    mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password_here';
    mysql> FLUSH PRIVILEGES;
    mysql> quit;
    


  5. Finally, shut down the MySQL service and start it back up.
    $ sudo systemctl restart mysql
    

All done. Your root password should now be changed and MySQL is back up and running as normal.

Conclusion

Resetting a forgotten MySQL root password is quite easy. However, the process does involve taking MySQL offline temporarily, so of course it’s best to avoid doing this more than absolutely necessary. If you happen to forget the password again, you’ll know where to find this guide.



Comments and Discussions
Linux Forum