By Mateusz Papiernik and Hazel Virdó
Forgetting passwords happens to the best of us. If you forget or lose the root password to your MySQL or MariaDB database, you can still gain access and reset the password if you have access to the server and a sudo
-enabled user account.
This tutorial will cover resetting the root password for older and newer versions of MySQL and MariaDB.
To recover your root MySQL/MariaDB password, you will need:
Most modern Linux distributions ship with either MySQL or MariaDB, a popular drop-in replacement that is fully compatible with MySQL. Depending on the database used and its version, you must use different commands to recover the root password.
You can check your version with the following command:
You’ll see some output like this with MySQL:
MySQL outputmysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrapper
Or output like this for MariaDB:
MariaDB outputmysql Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1
Note which database and version you’re running, as you’ll use them later. Next, you need to stop the database to access it manually.
To change the root password, you must shut down the database server beforehand.
You can do that for MySQL with:
And for MariaDB wtih:
After the database server is stopped, you’ll access it manually to reset the root password.
If you run MySQL and MariaDB without loading information about user privileges, you can access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.
To do this, you must stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip-networking to prevent other clients from connecting.
Start the database without loading the grant tables or enabling networking:
The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.
Now, you can connect to the database as the root user, which should not require a password.
You’ll immediately see a database shell prompt instead.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
Now that you have root access, you can change the root password.
One simple way to change the root password for modern versions of MySQL is using the ALTER USER
command. However, this command won’t work right now because the grant tables aren’t loaded.
Let’s tell the database server to reload the grant tables by issuing the FLUSH PRIVILEGES
command.
Now, we can change the root password.
Use the following command for MySQL 5.7.6 and newer and MariaDB 10.1.20 and newer.
For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:
Make sure to replace new_password
with your new password of choice.
Note: If the ALTER USER
command doesn’t work, it usually indicates a bigger problem. However, you can try UPDATE ... SET
to reset the root password.
Remember to reload the grant tables after this.
In either case, you should see confirmation that the command has been successfully executed.
OutputQuery OK, 0 rows affected (0.00 sec)
The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.
First, stop the instance of the database server that you started manually in Step 3. This command searches for the PID, or process ID, of MySQL or MariaDB process and sends SIGTERM
to tell it to exit smoothly after performing clean-up operations. You can learn more in this Linux process management tutorial.
For MySQL, use:
For MariaDB, use:
Then, restart the service using systemctl
.
For MySQL, use:
For MariaDB, use:
Now you can confirm that the new password has been applied correctly by running:
The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.
You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
This tutorial made my mysql database to not function. now I can’t even restart it, my site doesn’t even work now because it can’t connect to the database.
Please be more specific. At which step or steps did you encounter problems? Did you see any error messages? What happens when you try to restart the database?
The set of commands in the tutorial can result in setting a wrong root password by accident, but cannot result in corrupting the database and/or server configuration.
To help you with your problem more details are necessary.
It says now when I am trying mysql -u root -p
ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2 “No such file or directory”)
This means the database is not running at all. Please try
systemctl restart mysql
to restart MySQL and if it fails post the results oftail /var/log/mysql/error.log
.okay it’s working, but still the root password isn’t changed.
Maybe you have omitted one of the steps by accident. Try following the tutorial again step by step. If you don’t feel like doing this on a production server, create a fresh droplet with MySQL only to verify the steps in a safe environment first.
You can review the MySQL error log file (
error.log
) for any error messages or warnings that might indicate the cause of the connection issue. The error log file is typically located in the MySQL data directory (/var/log/mysql/error.log
or/var/log/mariadb/mariadb.log
).If the MySQL or MariaDB service is running but you’re still unable to connect, there may be an issue with the MySQL configuration. Check the MySQL configuration file (
my.cnf
ormy.ini
) to ensure that the socket file path is correct. The socket file path is typically specified under the[mysqld]
section. If the path is incorrect, update it to point to the correct location.Regards
Thank you very much for this tutorial. On CentOS with MySQL 5.7.17 when I launch the mysqld_safe --skip-grant-tables --skip-networking I get the folloqing message: mysqld_safe Directory ‘/var/run/mysqld’ for UNIX socket file don’t exist. After this, MySQL doesn’t start so when I try mysql -u root I get as an answer ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2). I’m stuck there as I cannot restart MySQL with --skip-grant-tables oprion enabled… Any clue?
do this before:
sudo mkdir /var/run/mysqld; sudo chown mysql /var/run/mysqld
It seems like there are two separate issues here: the missing directory for the UNIX socket file and the inability to start MySQL with the
--skip-grant-tables
option.You can create the directory manually using the following command:
Make sure to set the correct permissions for the directory:
After creating the directory, attempt to start MySQL again.
Once you have created the directory for the UNIX socket file, you can attempt to start MySQL with the
--skip-grant-tables
option again:If MySQL still fails to start with this option, there may be other issues with your MySQL configuration or installation.
You can heck the MySQL error log (
/var/log/mysql/error.log
or/var/log/mysqld.log
) for any error messages that might indicate the cause of the failure.You can also try starting MySQL without the
--skip-grant-tables
option to see if it starts successfully:Hope that this helps!
I didn’t omit any part, I found that when you are logged into the root account of the operating system, mysql no longer asks to enter the password of the root account of mysql.
There is a simple solution to login automatically, it’s to set your credentials in a file named .my.cnf in your user’s home directory.
And set your MySQL credentials like in the following example :
Then just use the command
mysql
to login into MySQL instead ofmysql -u root -p
. It also provide you the ability to use the other commands available with mysql-client likemysqldump
ormysqladmin
.Regards
Thanks for your article, This is a very useful post for us. For information only, Other may users also have a look at this link http://www.ipragmatech.com/forgot-mysql-root-password, this link also contains very easy step to reset the password.
I dunno, this didn’t work for me.
For Step 2, the server is using MariaDB but none of the mariadb-specific commands worked. Also it doesn’t know what ‘systemctl’ is. I figured out though that I could stop the database with ‘sudo service mysql stop’ - that definitely stopped the service.
In Step 3, ‘sudo mysqld_safe --skip-grant-tables --skip-networking &’ did something, but it didn’t kick me back to the command line. Although I didn’t have to ctrl-c it either, just when I tried typing the next bit was when the new line appeared. Don’t know if that’s a problem or not, I’m just not used to command line stuff.
In Step 4, ‘FLUSH PRIVELEGES;’ said the query was ok, but 0 rows affected. Then again, I don’t know if this is supposed to affect any rows. Next, the recommended way of changing the password did not work. I used the method where it says it’s indicative of bigger problems (whatever that means), and that did work and affect 1 row. Or it didn’t work because the guide says it should say 0 rows affected?
For Step 5, neither of the sudo kill commands worked. And of course the systemctl commands don’t work to restart the database, so I did ‘sudo service start mysql’. It said MariaDB started.
Then I tried the final step with ‘mysql -u root -p’ but it says the password is wrong. So I don’t know what I changed (if anything) but yeah, the guide didn’t work for me. At least I don’t have the same problems as NUCUTA?
Edit: I managed to change the password following Rackspace’s guide (https://support.rackspace.com/how-to/mysql-resetting-a-lost-mysql-root-password/). It’s almost the same, don’t know if the different order of mysql commands made a difference. I still used my own commands to start/stop the mysql service though - ‘sudo service mysql start’ or ‘sudo service mysql stop’
I had the same problem when I forgot one of my MySQL instance root password. I reset it using this guide.
https://www.fossgeek.org/server-configuration/reset-mysql-root-password/
It’s working fine & In my case I had a CentOS 6 box. :)
Thanks for sharing this information as other users might find it just helpful if they run into the same situation.
Regards
This comment has been deleted
Amaizing tutorial partner, rly! Thanks you so much…
Thank you the tutorial was actually very helpful.
I just have one question, in step 4 there is a note saying: “Note: If the ALTER USER command doesn’t work, it’s usually indicative of a bigger problem.”
What’s the bigger problem that’s mentioned and how can i solve it.
The note about the ALTER USER command not working and indicating a bigger problem typically suggests that there might be underlying issues with your MariaDB installation or configuration. Here are some potential reasons why the ALTER USER command might fail and how you can address them:
Incorrect Syntax: Double-check the syntax of the ALTER USER command to ensure that it is correct. Any typos or syntax errors can cause the command to fail. Pay attention to quotation marks, semicolons, and other syntax elements.
Insufficient Privileges: You need the appropriate privileges to execute the ALTER USER command. Make sure you are logged in as a user with the necessary privileges, such as the root user or another user with the ALTER USER privilege.
Socket Authentication: If your MariaDB installation is configured to use socket authentication for the root user, you might encounter issues when trying to set a password using the ALTER USER command. In such cases, you may need to switch to native authentication first using the mysql_native_password authentication plugin.
Database Corruption: In some cases, database corruption or other issues with the MySQL/MariaDB installation can prevent the ALTER USER command from working properly. You can try repairing the database or reinstalling MySQL/MariaDB to resolve any underlying issues.
Permissions and Ownership: Ensure that the MySQL/MariaDB data directory and files have the correct permissions and ownership. Improper permissions can prevent MariaDB from executing certain commands, including ALTER USER.
Version Compatibility: Make sure that the version of MariaDB you are using supports the ALTER USER command. Older versions may not support certain features or syntax used in the command.
If you encounter issues with the ALTER USER command, carefully review any error messages or warnings that are returned. These messages can provide valuable information about the underlying problem.
Regards
In Step 5, to prevent mysql> from freezing, it’s best to write: quit or \q and then restart: 'sudo systemctl start mysql, instead of writing: sudo kill
cat /var/run/mysqld/mysqld.pid
On the other hand I need to issue
sudo kill $(sudo cat /var/run/mysqld/mysqld.pid)
or actuallysudo kill (sudo cat /var/run/mysqld/mysqld.pid)
since my default shell is fish.If you just run mysql command under root user you will be granted access without asked for password, because socket authentication enabled for root@localhost.
The only way to set password is to swtch to native authentication like:
ALTER USER ‘root’@‘localhost’ IDENTIFIED WITH mysql_native_password BY ‘test’;
Thank you for the clarification. It seems like the authentication method for the root user in your MariaDB installation is set to use socket authentication, which allows the root user to access the database without providing a password.
To set a password for the root user and switch to native authentication, as you mentioned, you can use the following SQL command:
Replace
'new_password'
with the password you want to set for the root user.After executing this command, the root user will be required to provide a password when logging in to MariaDB using the
mysql
command-line client or other tools.Thank you for providing the correct approach for setting the root password in your MariaDB installation.
It was a bit touchy, but it worked for me… Here is my short version… https://gist.github.com/Artistan/7665d26aabd5f03772f6c0e6769a37ad
If you get the following error after running the
mysqld_safe
command…Try the following
Tried on Ubuntu 16.04
Exactly my error and your solution helped. Thanks million!
This helped me too, thanks! Ubuntu 18.04
Thanks for sharing this information.
The
var/run/mysqld
should be present and have the exact ownership. A common set of permissions is750
, which gives read, write, and execute permissions to the owner (mysql
), and read and execute permissions to the group.Regards
This tutorial isn’t working for MariaDB 10.2 as it makes the db no more working at all.
It is de facto like Nucuta has already described it In either case, you should see confirmation that the command has been successfully executed.
Output Query OK, 0 rows affected (0.00 sec) The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.
This means that nothing has been changed
root@go ~ # sudo mysqld_safe --skip-grant-tables --skip-networking & [1] 26402 root@go ~ # 171103 17:43:52 mysqld_safe Logging to ‘/var/lib/mysql/go.oo2.cloud.err’. 171103 17:43:52 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql mysql -u root Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 11 Server version: 10.2.10-MariaDB-10.2.10+maria~xenial mariadb.org binary distribution
Copyright © 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the current input statement.
MariaDB [(none)]> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)
Heya,
You can review the MariaDB error log (
/var/lib/mysql/*.err
) for any error messages or warnings that might indicate the cause of the issue. Look for any entries related to password changes or authentication failures.You can try resetting the root password again using the
mysql_secure_installation
script or by manually updating the password in the MySQL user table.Regards
Nice one, I get this error message:
Edit your my.cnf file (probably at /etc/mysql/mysql.conf.d/mysqld.cnf) to add the line skip-grant-tables
Then restart mysql service normally and follow steps above starting with mysql -u root
Remember to remove skip-grant-tables later (security!!!)
Command: sudo nano -w /etc/mysql/mysql.conf.d/mysqld.cnf More info: https://www.codero.com/knowledge-base/content/33/296/en/how-to-reset-your-root-mysql-password.html
Thanks for sharing this information. The skip-grant-tables tweak in the my.cnf file might just do the trick here and solve the issue indeed.
Regards
You can review the MySQL error log file (
error.log
) for any error messages or warnings that might indicate the cause of the connection issue. The error log file is typically located in the MySQL data directory (/var/log/mysql/error.log
or/var/log/mariadb/mariadb.log
).If the MySQL or MariaDB service is running but you’re still unable to connect, there may be an issue with the MySQL configuration. Check the MySQL configuration file (
my.cnf
ormy.ini
) to ensure that the socket file path is correct. The socket file path is typically specified under the[mysqld]
section. If the path is incorrect, update it to point to the correct location.Regards
I have been trying to setup a Password and Privileges for my New Raspberry Pi 3. I’m using Raspbian GNU/Linux" VERSION="9 (stretch) with 10.1.23-MariaDB, for debian-linux. You Instructions looked they would work but here are the Problems: Step 3: sudo mysqld_safe --skip-grant-tables --skip-networking & [1] 2874 pi@raspberrypi:~ $ 180218 12:39:56 mysqld_safe Logging to syslog. 180218 12:39:56 mysqld_safe A mysqld process already exists [1]+ Exit 1 sudo mysqld_safe --skip-grant-tables --skip-networking
mysql -u root ERROR 1698 (28000): Access denied for user ‘root’@‘localhost’
Step 4 Very End what is the command to save and get out of the MariaDB???
Nothing Works after: Restarting the Database Server Without Permission Checking Line Fails.
Can you help. I’ve tried for 5 days to get this Server Working. The Problems are with all the updates Raspbian has added to Apache2, MariaDB, PHP7, and PHPMyAdmin. I’ve reinstalled the OS 5 Times now.
Any help would really be appreciated.
Thanks
Joe
The error message “A mysqld process already exists” indicates that there is already a MySQL or MariaDB server process running on your system. You need to stop the existing MySQL/MariaDB server before running
mysqld_safe
with--skip-grant-tables
. You can stop the MySQL/MariaDB server using the following command:Once the server is stopped, you can proceed with running
mysqld_safe
:This command should start the MySQL/MariaDB server with the grant tables skipped.
After running
mysqld_safe
with--skip-grant-tables
, you should be able to log in to MySQL/MariaDB as the root user without a password. If you’re still encountering an “Access denied” error, it’s possible that there is another issue with the MySQL/MariaDB configuration. Try restarting the MySQL/MariaDB service and then attempt to log in again:If you continue to encounter the access denied error, there may be other configuration issues that need to be addressed.
To exit the MariaDB command-line interface, simply type
exit
and press Enter:This will exit the MariaDB command-line interface and return you to the terminal prompt.
Just tried this tutorial, but with some troubles at the step3, solved it with this tutorial: https://askubuntu.com/questions/172514/how-do-i-uninstall-mysql
There might have been updates to the tutorial to cover some minor issues that may occur. I believe the article should work just fine in it’s current revision.
Regards
It is working perfectly fine, but until i restart. Whenever I restart my system it stops working. What should i do to make the changes permanent. By the way im using kali linux.
Didnt work for me, at the -> mysql -u root I get this error and that’s the end of it…cant continue
Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’
You can review the MySQL error log file (
error.log
) for any error messages or warnings that might indicate the cause of the connection issue. The error log file is typically located in the MySQL data directory (/var/log/mysql/error.log
or/var/log/mariadb/mariadb.log
).If the MySQL or MariaDB service is running but you’re still unable to connect, there may be an issue with the MySQL configuration. Check the MySQL configuration file (
my.cnf
ormy.ini
) to ensure that the socket file path is correct. The socket file path is typically specified under the[mysqld]
section. If the path is incorrect, update it to point to the correct location.Regards
Thanks a lot Note : in some times in mariadb server you need to run mysql version commands
There might be a difference between the MySQL and MariaDB commands syntax so this is something to always keep in mind.
Regards
If you get “an’t connect to local MySQL server through socket” edit your my.cnf file (probably at /etc/mysql/mysql.conf.d/mysqld.cnf) to add the line skip-grant-tables
Then restart mysql service normally and follow steps above starting with mysql -u root
Remember to remove skip-grant-tables later (security!!!)
Command: sudo nano -w /etc/mysql/mysql.conf.d/mysqld.cnf More info: https://www.codero.com/knowledge-base/content/33/296/en/how-to-reset-your-root-mysql-password.html
Thanks for sharing this information as it may help other users who run into the same problem. Also thank you for taking your time to share the solution. You can always reach out in our community whenever you want to share something about SySadmin, DigitalOcean and beyond.
https://www.digitalocean.com/community/questions
Regards
please help me to resets my password for my phpmyadmin
You can reset the MySQL root password if the one in the file is not working or simply re-deploy the phpMyAdmin installation again.
We have an article on how to reset the MySQL/MariaDB root password which you can check here
https://www.digitalocean.com/community/tutorials/how-to-reset-your-mysql-or-mariadb-root-password
Regards
my database is not restating back, why?
$ sudo systemctl start mysql Job for mysql.service failed because the control process exited with error code. See “systemctl status mysql.service” and “journalctl -xe” for details.
My first approach will be to check the MySQL error log file for any additional information about the error. The error log file is typically located at
/var/log/mysql/error.log
. Review the contents of this file for any error messages or warnings that might help diagnose the problem.You can check this article on how to troubleshoot the most common MySQL errors
https://www.digitalocean.com/community/tutorial-series/how-to-troubleshoot-issues-in-mysql
Regards
also this happened $ sudo kill
cat /var/run/mysqld/mysqld.pid
cat: /var/run/mysqld/mysqld.pid: No such file or directoryThe
kill
command is used to send signals to processes. The correct syntax for killing a process with a known PID issudo kill PID
, wherePID
is the process ID of the process you want to terminate. It seems like you provided a file path (/var/run/mysqld/mysqld.pid
) instead of a PID.If you’re trying to stop a running process and don’t have the PID, you can use the
killall
command to kill processes by name. For example, to kill the MySQL server process, you can use:This command will terminate all processes with the name
mysqld
.Regards
The op need to put the supported Ubuntu version in the title, this article is for v16.04, it doesn’t work on v18.04.
After I tried to install Plesk (which failed) on my VPS my mysql root password was deleted. Instead an admin account was created with an unknown password. By creating a new password for the admin account I was able to connect to my database.
In such cases, it’s common for installation scripts to modify MySQL user accounts and configurations.
Since you were able to connect to your database using the admin account with a new password, you’ve already taken a good step forward. However, it’s important to ensure that your MySQL or MariaDB installation is in a secure state, especially if unexpected changes were made during the failed installation.
Regards
Doesn’t work.
“The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.”
No it doesn’t. Using latest MariaDB on CentOS8, it’s not in the background. The prompt is stuck in the window.
Also the “skin grant tables” doesn’t help. It doesn’t allow me to change the password.
If running a MySQL or MariaDB command with an ampersand (
&
) at the end doesn’t send the process to the background as expected, and you find that the prompt is stuck in the terminal window, it suggests that there may be some issues with the way the command is being executed.You can check if there are any custom shell configurations or aliases that might be affecting the behavior of the ampersand (
&
). Some configurations or aliases may override the default behavior of the ampersand.Regards
Boa Noite Senhoras e senhores da DigitalOcean [representados aqui pelo Mateusz (meu xará!], Muito mas muito obrigado mesmo, por vocês terem aparecido para mim, ótimos tutoriais!! me salvou! vamos que vamos!! saúde, sucesso, paz e amor a todas e a todos!
“Was this helpful?” …it was lifesaving mate! Cheers.
I’m getting the following error
The error message indicates that the MySQL client is unable to connect to the MySQL server through the Unix socket
/opt/bitnami/mariadb/tmp/mysql.sock
.You can double-check the path to the MySQL Unix socket file (
mysql.sock
). The default location for the MySQL socket file is usually/var/run/mysqld/mysqld.sock
. If your MySQL server is configured to use a different location, ensure that the MySQL client is configured to use the correct socket path.Also eview the MySQL configuration file (
my.cnf
ormy.ini
) to verify the socket path configuration. Look for thesocket
option in the[mysqld]
section of the configuration file. If thesocket
option is set to a different path, update it to the correct path.After making any changes to the MySQL configuration, restart the MySQL service to apply the changes:
The socket file should be owned by the MySQL user and group, and its permissions should allow the MySQL client to access it.
Regards