ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
What causes this
MySQL rejected your login. This happens when:
- The password is wrong or was recently changed
- The user doesn’t exist for the host you’re connecting from (
'root'@'localhost'vs'root'@'%'are different users in MySQL) - The user exists but doesn’t have privileges on the database you’re trying to access
- MySQL was installed with a random root password you never set (common on Ubuntu/Debian)
Fix 1: Double-check your credentials
# Try connecting with explicit credentials
mysql -u root -p
# Enter password when prompted — don't put it on the command line
If you’re connecting from code, make sure the password doesn’t have special characters that need escaping in your connection string.
Fix 2: Reset the root password
If you’ve lost the root password entirely:
# Stop MySQL
sudo systemctl stop mysql
# Start in safe mode (skips authentication)
sudo mysqld_safe --skip-grant-tables &
# Connect without a password
mysql -u root
# Reset the password
ALTER USER 'root'@'localhost' IDENTIFIED BY 'your-new-password';
FLUSH PRIVILEGES;
# Restart MySQL normally
sudo systemctl restart mysql
On MySQL 8+, if ALTER USER doesn’t work, try:
UPDATE mysql.user SET authentication_string='' WHERE User='root';
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your-new-password';
Fix 3: Check the user’s host
MySQL treats 'root'@'localhost' and 'root'@'127.0.0.1' as separate users. Check what exists:
SELECT User, Host FROM mysql.user WHERE User = 'root';
If you’re connecting from a Docker container or remote machine, you may need a user with @'%':
CREATE USER 'root'@'%' IDENTIFIED BY 'your-password';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';
FLUSH PRIVILEGES;
Fix 4: Grant the right privileges
The user exists but can’t access your specific database:
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
Check current grants with:
SHOW GRANTS FOR 'myuser'@'localhost';
How to prevent it
- Use environment variables for database credentials, never hardcode them
- Create application-specific users with minimal privileges instead of using root
- Document your MySQL credentials somewhere secure (password manager, secrets vault)
- When using Docker, set
MYSQL_ROOT_PASSWORDin your compose file so you always know the password