Changing the root password for MySQL

This guide shows how to change the password of the MySQL root user and other MySQL users, and how to reset the root password if you have lost it. The commands work for MySQL 5.7 and 8.x and for MariaDB 10.4 and newer. You need SSH access to the server.

How to Change the MySQL Root Password

Connect to MySQL as root:

mysql -u root -p

Press Enter and type the current root password. Then run:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
FLUSH PRIVILEGES;
quit

The root password is now new_password. Use a strong password instead of this example.

The same method works for other MySQL users. Put the user name instead of root, for example 'dovecot'@'localhost', and set a new password.

On Debian and Ubuntu, MariaDB or MySQL may be configured so that root logs in through the unix_socket plugin without a password. In this case, run sudo mysql instead of mysql -u root -p.

How to Reset a Lost MySQL Root Password

If you have lost the root password, you can reset it by starting MySQL without the privilege system. Connect to the server via SSH as root and follow these steps.

Step 1. Stop MySQL

On Ubuntu and Debian:

sudo systemctl stop mysql

On AlmaLinux, Rocky Linux and CentOS (the service may be called mysqld or mariadb):

sudo systemctl stop mysqld

Step 2. Start MySQL without password checks

Create the directory for the socket file if it does not exist, and give it to the mysql user:

sudo mkdir -p /var/run/mysqld
sudo chown mysql:mysql /var/run/mysqld

Start MySQL in safe mode. The --skip-networking option blocks remote connections while the server runs without passwords:

sudo mysqld_safe --skip-grant-tables --skip-networking &

The & at the end runs the command in the background, so you get the command prompt back. Check that the process is running:

jobs

Step 3. Set a new root password

Log in to MySQL as root. No password is needed at this stage:

mysql -u root

Reload the privilege tables and set a new password:

FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_root_password';
quit

The FLUSH PRIVILEGES command must come first: without it, ALTER USER does not work while the server runs with --skip-grant-tables.

Step 4. Restart MySQL normally

sudo pkill mysqld
sudo systemctl start mysql

Use mysqld instead of mysql in the last command on AlmaLinux, Rocky Linux and CentOS.

Now log in with the new password:

mysql -u root -p

If you need a server for your databases, take a look at our Linux VPS plans.

Blog
Subscribe to our Newsletter