Passwords are hard to remember, so if you have forgotten the MySQL root password, luckily, there is a way to change it. This post has been written for you, and by the end of this post, you will have successfully changed the password of MySQL.
This blog demonstrates how to reset the root password for MySQL and MariaDB databases installed with the apt package manager on Ubuntu. The procedure for changing the root password differs depending on whether you have MySQL installed and the default systemd configuration that ships with the distribution or packages from other vendors.
Before moving on to the answer, it is assumed that you have the latest version of the MySQL database for Ubuntu. This blog will offer an easy-to-follow guide for changing your MySQL root passwords in Ubuntu. Therefore, without wasting time, let's begin.
First, check the version of your MySQL because this post contains the solution of changing the root password on version 8 or higher. If the version of your MySQL is lower than 8, then the answer will be different. Run the following command:
MySQL Version Output:
mysql Ver 8.0.27-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))
To change the MySQL root password, you first need to shut down the MySQL server, run the following command:
sudo systemctl stop mysql.service
Check the status of the MySQL server to verify. Run the following command:
sudo systemctl status mysql.service
To start the MySQL server without granting the tables and networking check, set the environment variable MYSQLD_OPTS, which MySQL uses on startup. Run the following command:
sudo systemctl set-environment MYSQLD_OPTS="--skip-networking --skip-grant-tables"
Alright, the environment variable is a set, and we can log in to the MySQL shell providing no password.
After setting the environment variable MYSQLD_OPTS, start the MySQL service. Run the following command:
sudo systemctl start mysql.service
At this stage, we can access the MySQL database without a password:
sudo mysql -u root
Now, flush the privileges first. Run the following command:
sudo mysql -u root flush privileges;
Select the MySQL database. Run the following command:
ALTER USER 'root'@'localhost' IDENTIFIED BY '(YOUR NEW PASSWORD)';
First, kill all the processes of MySQL before even restarting the MySQL server.
sudo killall -u mysql
And the restart the MySQL server, run the following command:
sudo systemctl restart mysql.service
If all goes well, you should now be able to login to your MySQL database with a root password:
sudo mysql -u root -p