惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
T
Tailwind CSS Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
Secure Thoughts
博客园 - 【当耐特】
Know Your Adversary
Know Your Adversary
NISL@THU
NISL@THU
博客园 - 司徒正美
Last Week in AI
Last Week in AI
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy & Cybersecurity Law Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
B
Blog
The GitHub Blog
The GitHub Blog
小众软件
小众软件
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Spread Privacy
Spread Privacy
Martin Fowler
Martin Fowler
博客园 - 叶小钗
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Tenable Blog
S
Securelist
博客园 - 三生石上(FineUI控件)
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
罗磊的独立博客
T
Threat Research - Cisco Blogs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
F
Full Disclosure
Cloudbric
Cloudbric
The Cloudflare Blog
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog
Microsoft Azure Blog
Microsoft Azure Blog
H
Hacker News: Front Page
腾讯CDC
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
TaoSecurity Blog
TaoSecurity Blog
I
Intezer
The Last Watchdog
The Last Watchdog
G
GRAHAM CLULEY
Google Online Security Blog
Google Online Security Blog
T
The Blog of Author Tim Ferriss

DigitalOcean Community Tutorials

Mastering grep with Regular Expressions for Efficient Text Search It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu How To Use Struct Tags in Go apt-key Deprecation: Add Repositories with GPG on Ubuntu Linux ps Command: 20 Real-World Examples Python struct.pack and struct.unpack for Binary Data Deadlock in Java: Examples, Detection, and Prevention How To Use Find and Locate to Search for Files on Linux Structured Resume Skill Extraction Using Mistral-7B Inference How to Use the Python Main Function How to Set Up NemoClaw on a DigitalOcean Droplet with 1-Click Build an End-to-End RAG Pipeline for LLM Applications From Single to Multi-Agent Systems: Key Infrastructure Needs Back Up Data to Object Storage Using Restic How to Generate Videos with LTX-2.3 on DigitalOcean GPU Droplets How To Install LAMP Stack (Apache, MySQL, PHP) on Ubuntu How to Download Files with cURL How To Use Variadic Functions in Go Generate UUIDs with uuidgen on Linux How To Use EJS to Template Your Node Application How to Install Node.js on Ubuntu (Step-by-Step Guide) MongoDB Indexes: Improve Query Performance with Node.js LLM Tool Calling with DigitalOcean AI Platform and Databases What are Text Diffusion Models? - An Overview Crafting a Game from Scratch with GPT-5.4 Building Long-Term Memory in AI Agents with LangGraph and Mem0 How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04 Build a GraphQL API in Go to Upload Files to Spaces How To Lint and Format Code with ESLint in Visual Studio Code Train YOLO26 for Retail Object Detection on DigitalOcean GPUs How To Work with JSON in MySQL How to Use the JavaScript .map() Method Building a Scalable App with MongoDB Using DigitalOcean's MCP Server How to Create an SSH Key in Linux: Easy Step-by-Step Guide Measure MySQL Query Performance with mysqlslap How To Use *args and **kwargs in Python 3 Nemotron 3 helped me find the perfect dish rack? A2A vs MCP - How These AI Agent Protocols Actually Differ How To Install and Manage Supervisor Docker Container Images with Watchtower on Ubuntu Getting Started with Qwen3.5 Vision-Language Models How To Create a New Sudo-Enabled User on Ubuntu How to Use Ansible to Install and Set Up Docker on Ubuntu How To Enable Remote Desktop Protocol Using xrdp on Ubuntu 22.04 How To Convert a String to a List in Python How To Check If a String Contains Another String in Python How to Read a Properties File in Python Python Command Line Arguments: sys.argv, argparse, getopt Mastering Grep command in Linux/Unix: A Beginner's Tutorial Understanding Python Data Types How to Implement a Stack in C With Code Examples Python os.system() vs subprocess: Run System Commands How To Install and Use Docker Compose on Ubuntu How to Add and Delete Users on Ubuntu How To Order Query Results in Laravel Eloquent How To Define and Use Handlers in Ansible Playbooks How To Install and Use SQLite on Ubuntu How To Install and Use Homebrew on macOS How To Manage DateTime with Carbon in Laravel and PHP How To Install Git on Ubuntu How To Install and Secure Redis on Ubuntu How To Build and Install Go Programs on Linux Using ldflags to Set Version Information for Go Applications How To Build a Node.js Application with Docker How To Add JavaScript to HTML How To Add Images in Markdown How To Set Up a Production Elasticsearch Cluster with Ansible How To Set Up a Firewall Using firewalld on CentOS Understanding Systemd Units and Unit Files How To Set Up Replication in MySQL How To Use the .htaccess File
How To Reset Your MySQL or MariaDB Root Password
Mateusz Papiernik · 2016-12-21 · via DigitalOcean Community Tutorials

Introduction

You can reset your MySQL or MariaDB root password without the old password as long as you have access to the server and a sudo-capable user. This tutorial shows how to recover root using two methods: starting the server with --skip-grant-tables (and optionally --skip-networking), or the safer --init-file approach. It applies to MySQL 5.7+, MySQL 8.0+, MariaDB 10.1+, and MariaDB 10.4+, and has been verified on Ubuntu 20.04, 22.04, and 24.04, Debian 11 and 12, and RHEL/AlmaLinux/Rocky 8 and 9. The exact SQL and service names depend on your database and version, so the first step is to identify which one you are running.

Key Takeaways

  • Two main ways to reset the root password: start the server with --skip-grant-tables (and --skip-networking) to connect as root without a password, then set a new one via SQL. Use this method for quick recovery on non-production systems.
  • For production, use the --init-file method instead. Write the password-change SQL to a temp file, start the server with --init-file=/tmp/mysql-init-pwd.sql, then remove the file. The server starts with grant tables loaded, so no FLUSH PRIVILEGES is needed.
  • Auth plugin differences matter: MySQL 8.0+ defaults to caching_sha2_password (mysql_native_password removed in 8.4). MariaDB 10.4+ defaults to unix_socket for root, so a password reset may also require switching the auth plugin.

Prerequisites

  • Access to the Linux server where MySQL or MariaDB is installed.
  • A user account with sudo so you can stop and start the database service and run mysqld or mysqld_safe as needed.

The steps in this tutorial are valid for the following distributions and have been verified against current package versions:

  • Ubuntu 20.04, 22.04, and 24.04 with MySQL 8.0 from the Ubuntu APT repository or MySQL 8.4 from the MySQL APT repository, and MariaDB 10.x from the MariaDB APT repository.
  • Debian 11 and 12 with MySQL 8.0 or MariaDB 10.x.
  • RHEL, CentOS Stream, AlmaLinux, and Rocky Linux 8 and 9 with MySQL 8.0 from the MySQL RPM repository or MariaDB 10.x from the MariaDB RPM repository.

If your distribution installs MySQL from the default OS repository, it will typically be MySQL 8.0 on Ubuntu 22.04+, Ubuntu 24.04, and Debian 12. On Ubuntu 20.04, the default is MySQL 8.0 as well. On RHEL 8/9 and derivatives, the default module stream is MySQL 8.0. Verify your version with mysql --version in Step 1.

Note: These steps require direct SSH access to the server and root-level OS permissions. They do not apply to managed database services such as DigitalOcean Managed Databases, Amazon RDS, or any hosted database where you do not have OS-level access.

If you need to install the server first, see our guide on installing MySQL on Ubuntu.

Step 1 — Identifying the Database Version

The commands and SQL you use depend on whether you run MySQL or MariaDB and which version. Check with:

mysql --version

Use the output to choose the right instructions later:

  • MySQL 8.0 or newer: You will use ALTER USER ... IDENTIFIED WITH caching_sha2_password BY '...';. On many systems, mysqld_safe is not available; use sudo -u mysql mysqld --skip-grant-tables --skip-networking or the --init-file method.
  • MySQL 5.7.x: You will use ALTER USER 'root'@'localhost' IDENTIFIED BY '...';. You can use mysqld_safe --skip-grant-tables --skip-networking if available.
  • MariaDB 10.4 or newer: Root may use unix_socket auth; if you need a password, use ALTER USER and optionally set the plugin to mysql_native_password.
  • MariaDB 10.1.20 and newer (including 10.2, 10.3): ALTER USER 'root'@'localhost' IDENTIFIED BY '...'; is valid.

Example output for MySQL 5.7:

mysql  Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using  EditLine wrapper

Example output for MySQL 8:

mysql  Ver 8.0.35 for Linux on x86_64 (MySQL Community Server - GPL)

Example output for MariaDB:

mysql  Ver 15.1 Distrib 10.5.21-MariaDB, for Linux (x86_64) using readline 5.1

Step 2 — Stopping the Database Server

Stop the database service so you can start it manually with privilege checking disabled. The service name depends on your OS and whether you run MySQL or MariaDB:

  • Debian/Ubuntu (MySQL): service name is mysql.
  • RHEL/CentOS/AlmaLinux/Rocky (MySQL): service name is mysqld. PID file is often /var/run/mysqld/mysqld.pid or under /var/lib/mysql/ depending on distro.
  • MariaDB (all supported distros): service name is mariadb.

Examples:

MySQL on Debian/Ubuntu:

sudo systemctl stop mysql

MySQL on RHEL/CentOS/AlmaLinux/Rocky:

sudo systemctl stop mysqld

MariaDB:

sudo systemctl stop mariadb

Confirm the service has stopped:

MySQL:

sudo systemctl status mysql

MariaDB:

sudo systemctl status mariadb

A stopped service shows Active: inactive (dead) in the output. Then proceed to start the server without grant tables.

Step 3 — Restarting the Database Server Without Permission Checking

Start the server with --skip-grant-tables and --skip-networking. This tells MySQL or MariaDB to skip loading user privilege data entirely, which lets you connect as root locally without a password. The --skip-networking flag ensures no remote clients can connect while the server is in this unprotected state.

MySQL 5.7 (when mysqld_safe is available):

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

The & runs the process in the background so you can keep using the terminal.

MySQL 8.0+ (no mysqld_safe on many systems):

On distributions where mysqld_safe was removed, start mysqld directly:

sudo -u mysql mysqld --skip-grant-tables --skip-networking &

Security: --skip-grant-tables disables authentication. Always use --skip-networking so the server does not accept network connections. Run the reset as quickly as possible. For production, prefer the Alternative Method: Using --init-file below.

MariaDB:

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

If you see mysqld_safe: command not found, use sudo -u mysql mysqld --skip-grant-tables --skip-networking & as for MySQL 8.

Connect as root (no password):

mysql -u root

You should get a prompt immediately.

MySQL:

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

MariaDB:

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Step 4 — Changing the Root Password

With grant tables skipped, the server does not know any access rules and refuses to apply changes to them. The grant tables are what MySQL and MariaDB use to decide who can do what. Reload them first so the server can process your password change:

  1. FLUSH PRIVILEGES;

Then set the new password using the statement that matches your version.

MySQL 8.0+ (default auth plugin is caching_sha2_password; mysql_native_password is deprecated in 8.0 and removed in 8.4):

  1. ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'new_password';

For full syntax reference, see the MySQL 8.0 ALTER USER documentation and the MariaDB ALTER USER documentation.

MySQL 5.7.6 and newer (not 8.0):

  1. ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

MariaDB 10.4+ (if root uses unix_socket and you want password-based auth, set plugin and password):

On MariaDB 10.4+, root authentication defaults to unix_socket. This means MariaDB checks your Linux user identity instead of a password. If you are running as the system root user, MariaDB lets you in without one. If you need password-based access (for example, for an application connecting as root), you must explicitly switch the auth plugin.

  1. ALTER USER 'root'@'localhost' IDENTIFIED VIA mysql_native_password USING PASSWORD('new_password');

Or to only set the password and keep the existing plugin:

  1. ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

Note: To confirm the plugin was updated correctly, run: SELECT user, host, plugin FROM mysql.user WHERE user='root'; after reconnecting normally.

MariaDB 10.1.20 and newer (10.1, 10.2, 10.3):

  1. ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

MySQL 5.7.5 and older / MariaDB 10.1.19 and older:

  1. SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');

Replace new_password with your chosen password. Success looks like:

Query OK, 0 rows affected (0.00 sec)

Note: If ALTER USER is not available or fails, you can try updating the grant table directly (MySQL 5.7 / MariaDB): UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost'; then run FLUSH PRIVILEGES; again. Prefer ALTER USER when your version supports it.

Step 5 — Restarting the Database Server Normally

Stop the manually started MySQL or MariaDB process. Find its PID and send SIGTERM so it shuts down cleanly.

MySQL or MariaDB:

sudo kill $(cat /var/run/mysqld/mysqld.pid)

Note: If the PID file path differs on your distribution, use sudo mysqladmin -u root -p shutdown as a reliable alternative for both MySQL and MariaDB. To find your PID file location, check the pid-file directive in your MySQL configuration:

grep pid-file /etc/my.cnf /etc/mysql/my.cnf 2>/dev/null

Then start the service again.

MySQL on Debian/Ubuntu:

sudo systemctl start mysql

MySQL on RHEL/CentOS/AlmaLinux/Rocky:

sudo systemctl start mysqld

MariaDB:

sudo systemctl start mariadb

Verify the new password:

mysql -u root -p

Enter the new password when prompted. A successful login looks like this:

MySQL:

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

MariaDB:

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

If you see ERROR 1045 (28000): Access denied for user 'root'@'localhost', see Troubleshooting Common Errors below.

The --init-file method runs a SQL file once at server startup, sets the new password, and then you remove the file. The server starts with grant tables loaded and full authentication active throughout. You never expose an unauthenticated instance to the network, which makes this the safer choice for production systems.

  1. Create a temporary SQL file (e.g. /tmp/mysql-init-pwd.sql) with the appropriate statement. Use one of the following, then replace new_password with your real password.

    MySQL 8.0+:

    ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'new_password';
    

    MySQL 5.7 (and MariaDB 10.1.20+ with standard auth):

    ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
    

    MariaDB 10.4+ (to set password and use mysql_native_password):

    ALTER USER 'root'@'localhost' IDENTIFIED VIA mysql_native_password USING PASSWORD('new_password');
    
  2. Stop the database service using the command for your distro from Step 2:

    • MySQL on Debian/Ubuntu: sudo systemctl stop mysql
    • MySQL on RHEL/CentOS/AlmaLinux/Rocky: sudo systemctl stop mysqld
    • MariaDB: sudo systemctl stop mariadb
  3. Start the server with the init file (run from a terminal, not as a background job so you can see when it has done the init):

    sudo -u mysql mysqld --init-file=/tmp/mysql-init-pwd.sql
    

    Wait for the server to finish starting. Since the process is running in the foreground, the output appears directly in your terminal. Look for a line like:

    [Note] mysqld: ready for connections.
    

    Once you see it, stop the server cleanly using the appropriate command for your distro. Open a second terminal to run the stop command. Do not use Ctrl+C or SIGINT in the terminal where mysqld is running.

    MySQL on Debian/Ubuntu:

    sudo systemctl stop mysql
    

    MySQL on RHEL/CentOS/AlmaLinux/Rocky:

    sudo systemctl stop mysqld
    

    MariaDB:

    sudo systemctl stop mariadb
    

    If systemctl cannot stop the manually started process, use sudo mysqladmin -u root -p shutdown (you will be prompted for the new password you just set), or send SIGTERM directly:

    sudo kill $(cat /var/run/mysqld/mysqld.pid)
    

    Note: Because the server starts with grant tables loaded when using --init-file, you do not need to run FLUSH PRIVILEGES. The ALTER USER statement takes effect immediately.

  4. Remove the init file so the password is not left on disk:

    sudo rm /tmp/mysql-init-pwd.sql
    
  5. Start the service normally and test login.

    MySQL on Debian/Ubuntu:

    sudo systemctl start mysql
    

    MySQL on RHEL/CentOS/AlmaLinux/Rocky:

    sudo systemctl start mysqld
    

    MariaDB:

    sudo systemctl start mariadb
    

    Then confirm the new password works:

    mysql -u root -p
    

Troubleshooting Common Errors

ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option

This appears when you run ALTER USER (or other privilege-changing statements) before reloading the grant tables. With --skip-grant-tables, the server does not apply privilege changes until you run FLUSH PRIVILEGES;. Run FLUSH PRIVILEGES; first, then run your ALTER USER (or SET PASSWORD) again.

ERROR 1524 (HY000): Plugin 'unix_socket' is not loaded

On MariaDB, root is often configured to use unix_socket authentication. If the socket plugin is not loaded or there is a configuration issue, you can see this error. Ensure you are connecting as the system root user (or the same OS user that owns the socket). To switch to password-based auth, use ALTER USER 'root'@'localhost' IDENTIFIED VIA mysql_native_password USING PASSWORD('...'); as in Step 4.

mysqld_safe: command not found

On MySQL 8.0+, many packages no longer ship mysqld_safe. Use sudo -u mysql mysqld --skip-grant-tables --skip-networking & instead, or use the –init-file method.

Access denied for user 'root'@'localhost' after reset

This is usually an authentication plugin mismatch. For example, the client or another service expects mysql_native_password but the server now uses caching_sha2_password for root.

If you can log in, check the plugin directly:

mysql -u root -p -e "SELECT user, host, plugin FROM mysql.user WHERE user='root';"

If you cannot log in at all, re-enter the skip-grant-tables session to diagnose without a password. Stop the service, restart with --skip-grant-tables --skip-networking as in Step 3, connect with mysql -u root, then run:

  1. SELECT user, host, plugin FROM mysql.user WHERE user='root';

Once you know the plugin, run the correct ALTER USER statement from Step 4 to set both the password and the plugin your client expects, then restart the service normally.

FAQ

Q: How do I reset the MySQL root password without the old password?

A: Stop the MySQL service, restart it with --skip-grant-tables and --skip-networking, connect as root without a password, run FLUSH PRIVILEGES, then use ALTER USER to set the new password. Full steps are in this tutorial.

Q: What is the difference between resetting the root password in MySQL vs MariaDB?

A: The SQL syntax is nearly identical for recent versions, but MariaDB 10.4+ uses unix_socket authentication for root by default, which means a password may not be required for local root login at all. If you need password-based auth, you must explicitly change the auth plugin.

Q: Why does ALTER USER fail after skip-grant-tables?

A: When MySQL or MariaDB starts with --skip-grant-tables, privilege-related SQL functions are disabled. You must run FLUSH PRIVILEGES first to reload the grant tables before ALTER USER will execute successfully.

Q: Is it safe to use --skip-grant-tables?

A: Only in a controlled environment. The --skip-grant-tables option disables all authentication and, without --skip-networking, exposes the database to any network client. Always pair it with --skip-networking and perform the reset as quickly as possible. For production servers, the --init-file method is safer.

Q: How do I reset the MySQL root password on Ubuntu?

A: On Ubuntu, the MySQL service name is mysql. Stop it with sudo systemctl stop mysql, follow the skip-grant-tables steps in this tutorial, then restart with sudo systemctl start mysql.

About the Author

This tutorial was written and validated by a technical writer with hands-on experience administering MySQL and MariaDB on Linux production systems, including version migrations, authentication plugin changes, and database recovery operations. It was reviewed and updated to reflect current behavior in MySQL 8.0+ and MariaDB 10.4+.

Conclusion

After resetting the root password, confirm login with mysql -u root -p. For day-to-day use, create a dedicated MySQL user with limited privileges instead of using root; see creating a new MySQL user and granting permissions. To protect your data, set up backing up your MySQL databases on a regular schedule.

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.