MySQL Change MySQL root password in Linux

Example

To change MySQL's root user password:

Step 1: Stop the MySQL server.

  • in Ubuntu or Debian:
    sudo /etc/init.d/mysql stop
  • in CentOS, Fedora or Red Hat Enterprise Linux:
    sudo /etc/init.d/mysqld stop

Step 2: Start the MySQL server without the privilege system.

sudo mysqld_safe --skip-grant-tables &

or, if mysqld_safe is unavailable,

sudo mysqld --skip-grant-tables &

Step 3: Connect to the MySQL server.

mysql -u root

Step 4: Set a new password for root user.

5.7
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
FLUSH PRIVILEGES;
exit;
5.7
FLUSH PRIVILEGES;
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
FLUSH PRIVILEGES;
exit;

Note: The ALTER USER syntax was introduced in MySQL 5.7.6.

Step 5: Restart the MySQL server.

  • in Ubuntu or Debian:
    sudo /etc/init.d/mysql stop
    sudo /etc/init.d/mysql start
  • in CentOS, Fedora or Red Hat Enterprise Linux:
    sudo /etc/init.d/mysqld stop
    sudo /etc/init.d/mysqld start