ERROR 1045 (28000): Access denied for user 'root'@'localhost' - 10 Causes and Fixes

ERROR 1045 (28000): Access denied for user 'root'@'localhost' means MySQL received your connection, looked up an account that matches the user name and the host you appear to be coming from, and refused the credentials you presented. The connection itself worked - this is not a networking problem, and ERROR 1045 (28000): Access denied for user 'root'@'localhost' will never be fixed by opening a port.

The word (using password: YES) or (using password: NO) at the end of the real message is the single most useful token in it. NO means no password reached the server at all; YES means one did and it did not match the stored credential for the matched account.

There are two independent things MySQL must get right before it lets you in: which account row it matches (user name plus host pattern) and whether the authentication plugin on that row accepts your secret. Almost every occurrence of 1045 is one of those two going wrong. This page walks the common causes in order, each with a reproduction, the lines that fix it, and a way to confirm.

Every command below is plain MySQL/MariaDB SQL or standard client flags. Nothing here depends on an unreleased feature. A tech-savvy adult using a laptop at night with neon lighting, creating a cyberpunk ambiance.

ErrorERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Where it happensMySQL and MariaDB servers, any version, from the mysql CLI, mysqladmin, or any client driver (JDBC, PyMySQL, mysql2, PDO). SQLSTATE 28000 = invalid authorization specification.
What it meansThe server matched an account for this user name and host, and then rejected the password or auth method you offered - or it matched no account at all, which it reports identically for security reasons.

The Fast Fix

If you own the box and just need back in, reset the root password using --skip-grant-tables, then re-authenticate.

Stop the server, start it without privilege checks, and set a new password:

sudo systemctl stop mysql
sudo mysqld_safe --skip-grant-tables --skip-networking &
mysql -u root
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewStrongPass!23';

FLUSH PRIVILEGES must come before ALTER USER - with --skip-grant-tables the grant tables are not loaded, and ALTER USER fails until you load them. Then kill mysqld_safe, start the service normally, and log in with the new password.

If you do not control the server, skip to the diagnostic checklist - your 1045 is almost certainly a host-pattern or auth-plugin mismatch, not a forgotten password.

What Is Actually Causing It

1. Wrong password, or a shell that mangled it

Reproduce it

# Password contains ! and $ - the shell eats them before mysql sees it
mysql -u root -pP@ss!word$1
# ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Why it happens — In an interactive bash/zsh session, ! triggers history expansion and $1 expands to a positional parameter (usually empty). The client sends a different string than you typed, so the hash comparison fails.

The fix

# Let the client prompt - nothing passes through the shell
mysql -u root -p
Enter password: 

Changed: dropped the inline password entirely. If you must inline it, single-quote it: mysql -u root -p'P@ss!word$1'. Never leave a space after -p.

Confirm it worked — Run echo "-p$MYPASS" (or echo '-pP@ss!word$1') and compare it character by character with the password you set. If they differ, the shell was the problem.


2. A space between -p and the password

Reproduce it

mysql -u root -p secretpass
# ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Why it happens — -p takes its value immediately adjacent, with no space. With a space, MySQL reads -p as "prompt me" and treats secretpass as the database name. Non-interactive shells get an empty password, hence using password: NO.

The fix

mysql -u root -psecretpass
# or, safer:
mysql -u root -p

Changed: removed the space. -u tolerates a space, -p does not - that asymmetry is the whole trap.

Confirm it worked — Look at the tail of the error. using password: NO while you believe you supplied one is almost always this or an unread config file.


3. root uses auth_socket, so passwords are irrelevant

Reproduce it

# Fresh Debian/Ubuntu install, logged in as a normal user
mysql -u root -p
Enter password: whateveryoutyped
# ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Why it happens — Debian and Ubuntu packages create root@localhost with the auth_socket plugin (unix_socket on MariaDB). That plugin ignores passwords and only accepts connections whose OS user name equals the MySQL user name. As a non-root OS user you can never satisfy it.

The fix

sudo mysql
-- Confirm, then switch to password auth if you need it
SELECT user, host, plugin FROM mysql.user WHERE user = 'root';
ALTER USER 'root'@'localhost'
  IDENTIFIED WITH caching_sha2_password BY 'NewStrongPass!23';
FLUSH PRIVILEGES;

Changed: sudo makes your OS user root, which satisfies auth_socket. On MariaDB use IDENTIFIED VIA mysql_native_password USING PASSWORD('NewStrongPass!23').

Confirm it worked — SELECT user, host, plugin FROM mysql.user WHERE user='root'; - if plugin reads auth_socket or unix_socket, only the matching OS user can connect.


4. Host 'localhost' resolved to TCP 127.0.0.1, matching a different account

Reproduce it

# Account exists only as root@localhost, but this forces TCP
mysql -u root -p -h 127.0.0.1
# ERROR 1045 (28000): Access denied for user 'root'@'127.0.0.1' (using password: YES)

Why it happens — MySQL treats localhost and 127.0.0.1 as different hosts in the grant tables. -h localhost uses a Unix socket and matches 'root'@'localhost'; -h 127.0.0.1 opens a TCP connection and needs 'root'@'127.0.0.1' or a wildcard row.

The fix

mysql -u root -p -h localhost --protocol=SOCKET

Or create the account the client actually needs:

CREATE USER 'root'@'127.0.0.1' IDENTIFIED BY 'NewStrongPass!23';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' WITH GRANT OPTION;
FLUSH PRIVILEGES;

Changed: either force the socket transport, or add the row for the host the server reports.

Confirm it worked — Read the host in the error message itself - it is the host the server matched against. SELECT user, host FROM mysql.user; must contain a row whose host covers it.


5. No account row exists for that user/host pair at all

Reproduce it

-- Only root@localhost exists
SELECT user, host FROM mysql.user;
-- +------+-----------+
-- | root | localhost |
mysql -u appuser -p -h localhost
# ERROR 1045 (28000): Access denied for user 'appuser'@'localhost' (using password: YES)

Why it happens — MySQL deliberately returns the same 1045 for "no such account" and "wrong password" so an attacker cannot enumerate user names. A typo in the user name produces an identical message to a wrong password.

The fix

CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'AppPass!23';
GRANT ALL PRIVILEGES ON appdb.* TO 'appuser'@'localhost';
FLUSH PRIVILEGES;

Changed: the account now exists for the exact user/host pair the client presents.

Confirm it worked — SELECT user, host, plugin FROM mysql.user ORDER BY user; - the pair in your error message must appear, or be covered by a % host row.


6. Anonymous ''@'localhost' row shadows your account

Reproduce it

SELECT user, host FROM mysql.user WHERE host = 'localhost';
-- +----------+-----------+
-- |          | localhost |   <- anonymous
-- | appuser  | %         |
mysql -u appuser -p -h localhost
# ERROR 1045 (28000): Access denied for user 'appuser'@'localhost' (using password: YES)

Why it happens — An empty user name matches any user name. MySQL sorts candidate rows most-specific-host-first, so ''@'localhost' beats 'appuser'@'%', and your password is then checked against the anonymous account's (usually empty) credential.

The fix

DROP USER ''@'localhost';
FLUSH PRIVILEGES;

Or add the specific row so it wins on user name:

CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'AppPass!23';

Changed: removed the catch-all row that was absorbing the match. Old tutorial installs and mysql_install_db on some distros create these.

Confirm it worked — SELECT user, host FROM mysql.user WHERE user = ''; must return zero rows. Then reconnect from the same host.


More causes (6 remaining)

7. Client cannot speak caching_sha2_password

Reproduce it

# Old client or old driver against a MySQL 8 account
mysql -u appuser -p -h db.internal
# ERROR 1045 (28000): Access denied for user 'appuser'@'db.internal' (using password: YES)
SELECT user, host, plugin FROM mysql.user WHERE user = 'appuser';
-- | appuser | % | caching_sha2_password |

Why it happens — MySQL 8 defaults new accounts to caching_sha2_password. A client built only for mysql_native_password cannot complete that handshake and the server reports it as 1045 rather than a distinct plugin error. Over an unencrypted TCP connection the plugin also needs the server's RSA public key; without it the exchange fails.

The fix

ALTER USER 'appuser'@'%'
  IDENTIFIED WITH mysql_native_password BY 'AppPass!23';
FLUSH PRIVILEGES;

Or, better, keep the stronger plugin and fix the client - upgrade the driver, or enable TLS so the handshake can carry the password safely.

Changed: the account's plugin now matches what the client can negotiate. mysql_native_password is weaker; prefer upgrading the driver when you can.

Confirm it worked — Compare SELECT plugin FROM mysql.user WHERE user='appuser'; against your driver's documented support. Confirm the server offers the plugin with SHOW PLUGINS;.


8. A stale ~/.my.cnf or MYSQL_PWD overrides your flags

Reproduce it

# ~/.my.cnf left over from last month
[client]
user = root
password = oldpassword
mysql -u root -p
Enter password: CorrectPass!23
# ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Why it happens — The client reads option files (/etc/my.cnf, /etc/mysql/my.cnf, ~/.my.cnf) and the MYSQL_PWD environment variable. Depending on read order a stale value can win over what you typed, and the [client] section applies to every MySQL client on the box.

The fix

# Prove it by ignoring every option file
mysql --no-defaults -u root -p

Then correct the file:

[client]
user = root
password = CorrectPass!23

Changed: --no-defaults isolates the cause; after that, update or delete the stale credential. Also check echo $MYSQL_PWD.

Confirm it worked — mysql --print-defaults lists exactly which options the client will apply, including the user and password it picked up.


9. Connecting to a different server than you think

Reproduce it

# Local socket is fine, but a tunnel or container forwards 3306 elsewhere
mysql -u root -p -h 127.0.0.1 -P 3306
# ERROR 1045 (28000): Access denied for user 'root'@'10.0.3.17' (using password: YES)

Why it happens — An SSH tunnel, a Docker port mapping, or a second mysqld on another port means your credentials are hitting a different instance with its own grant tables. The host in the error is the address that instance sees, which is why it often looks nothing like your machine.

The fix

# Confirm which endpoint actually answers
ss -lntp | grep 3306
mysql -u root -p --protocol=SOCKET -S /var/run/mysqld/mysqld.sock

Changed: pinned the connection to an explicit socket path instead of a port that something else may own.

Confirm it worked — Connect with any working account and run SELECT @@hostname, @@port, @@socket;. If those do not describe the server you intended, your credentials were never wrong.


10. Account is locked or its password has expired

Reproduce it

SELECT user, host, account_locked, password_expired
  FROM mysql.user WHERE user = 'appuser';
-- | appuser | % | Y | N |
mysql -u appuser -p
# ERROR 1045 (28000): Access denied for user 'appuser'@'localhost' (using password: YES)

Why it happens — ALTER USER ... ACCOUNT LOCK and an exhausted password lifetime both block authentication. A locked account surfaces as 1045 even though the password is perfectly correct, which is why password resets appear to do nothing.

The fix

ALTER USER 'appuser'@'%' ACCOUNT UNLOCK;
ALTER USER 'appuser'@'%' IDENTIFIED BY 'AppPass!23' PASSWORD EXPIRE NEVER;
FLUSH PRIVILEGES;

Changed: cleared the lock and reset the expiry policy. account_locked exists on MySQL 5.7+; on older servers and MariaDB check max_connections/max_user_connections limits in the same row instead.

Confirm it worked — Re-run the SELECT above - account_locked and password_expired must both read N, then reconnect.


11. Password set with a plaintext string in a hash position

Reproduce it

-- Wrong: the literal text is stored as if it were a hash
SET PASSWORD FOR 'appuser'@'localhost' = 'AppPass!23';
mysql -u appuser -p
# ERROR 1045 (28000): Access denied for user 'appuser'@'localhost' (using password: YES)

Why it happens — Older MySQL (5.6 and earlier) and some MariaDB paths expect a hash on the right-hand side of SET PASSWORD, not a plaintext string. The literal gets stored verbatim, so no real password can ever hash to it. The same thing happens when you copy a hash into IDENTIFIED BY instead of IDENTIFIED BY PASSWORD.

The fix

-- Portable and unambiguous on MySQL 5.7+ / 8.x
ALTER USER 'appuser'@'localhost' IDENTIFIED BY 'AppPass!23';
FLUSH PRIVILEGES;

Changed: ALTER USER ... IDENTIFIED BY always treats the value as plaintext and hashes it with the account's plugin. Use it instead of SET PASSWORD unless you know the server's exact semantics.

Confirm it worked — SELECT user, host, LENGTH(authentication_string) FROM mysql.user WHERE user='appuser'; - a real hash is a long fixed-width string, not the length of your typed password.


12. Client sends an unexpected default user name

Reproduce it

import pymysql
# user omitted - driver falls back to the OS login name
conn = pymysql.connect(host="localhost", password="AppPass!23", database="appdb")
# pymysql.err.OperationalError: (1045, "Access denied for user 'deploy'@'localhost' (using password: YES)")

Why it happens — When the user name is missing, clients and drivers substitute the OS user (or ODBC on Windows). The server then matches a row for that name, which usually does not exist, and reports 1045 against a name you never typed.

The fix

import pymysql
conn = pymysql.connect(
    host="localhost",
    user="appuser",          # explicit, never inferred
    password="AppPass!23",
    database="appdb",
)

Changed: set user explicitly. Same rule for JDBC URLs, mysql2 configs, and DSN strings.

Confirm it worked — Read the user name inside the error message. If it is your OS login or ODBC, the client never sent the name you intended.

Detailed image of a server rack with glowing lights in a modern data center. ## None of Those? Narrow It Down
  1. Read the tail of the message. (using password: NO) means no password reached the server - look at -p spacing, a missing password key in your driver config, or an option file; stop looking at the stored credential. (using password: YES) means one arrived and was rejected, so continue.
  2. Read the user and host inside the message, not what you typed. They are what the server matched. A host you do not recognise means you are talking to a different instance or arriving over a different transport; a user name you did not type means the client defaulted it.
  3. Run mysql --print-defaults, then retry with mysql --no-defaults -u <user> -p. If --no-defaults succeeds, an option file or MYSQL_PWD was supplying stale credentials, and nothing is wrong with the account.
  4. Get in some other way - sudo mysql on Debian/Ubuntu, or any account that works - and run SELECT user, host, plugin FROM mysql.user ORDER BY user, host;. No row covering your user/host pair means the account does not exist; that rules out every password theory.
  5. Check for shadowing with SELECT user, host FROM mysql.user WHERE user = '';. Any row here means an anonymous account may be absorbing your match before your own row is considered.
  6. Compare the matched row's plugin against what your client supports. auth_socket/unix_socket rules out passwords entirely; caching_sha2_password with an old driver rules in a handshake failure rather than a wrong secret.
  7. Check SELECT account_locked, password_expired FROM mysql.user WHERE user = '<user>' AND host = '<host>';. A Y in either column explains a 1045 that survives repeated correct password resets.
  8. If every step above is clean, confirm you are on the intended server: connect with any working account and run SELECT @@hostname, @@port, @@socket;. A surprise here means your credentials were always correct and pointed at the wrong place.

Why This Error Exists At All

MySQL authentication is a two-key lookup, not a one-key one. Every row in mysql.user is identified by the pair (user, host) - the account is not root, it is 'root'@'localhost'. When a connection arrives, the server resolves the client's address, builds a candidate list of rows whose user name and host pattern both match, and sorts them most specific first: literal hosts beat patterns, and a non-empty user name beats the empty one. It then tries the single winning row and nothing else. That last part is the design decision most people get wrong. MySQL does not fall through to the next candidate when the password fails. If ''@'localhost' wins the sort, your perfectly correct 'appuser'@'%' password is never consulted.

The second decision is deliberate opacity. "No such user" and "wrong password" return the identical code 1045 with the identical wording. That is not sloppiness - distinguishing them would turn the login endpoint into a user-name oracle, letting an attacker confirm that root or backup_svc exists before spending any effort on passwords. The price you pay for that security property is a diagnostic that cannot tell you which half of the two-key lookup failed. This is why the productive move is never "try the password again" but "go look at mysql.user with an account that works" - you have to inspect the state the error refuses to describe.

The third decision is that authentication is pluggable, and the plugin lives on the account row. auth_socket checks your OS identity and ignores passwords. caching_sha2_password runs a challenge-response that needs either TLS or the server's RSA key. mysql_native_password does the old SHA1-based handshake. A client that cannot complete the row's chosen handshake produces the same 1045, because from the server's point of view authentication simply did not succeed. Once you hold all three ideas - pair lookup with no fallback, intentional ambiguity, per-account plugin - the entire 1045/1044/1130 family stops being mysterious. 1130 means the host never matched any row and was refused before credentials; 1045 means a row matched and the credential step failed; 1044 means you authenticated fine and lack privilege on a specific database. Each one tells you exactly how far through the gate you got. Close-up of a computer monitor displaying cyber security data and code, indicative of system hacking or programming.

Stop It From Coming Back

  • Create accounts with explicit host patterns and never rely on % for admin users: CREATE USER 'appuser'@'10.0.%' IDENTIFIED BY .... Checking SELECT user, host FROM mysql.user into version control as a migration makes host drift visible in code review.
  • Drop anonymous and test accounts at provisioning time. mysql_secure_installation does this, or run DELETE FROM mysql.user WHERE user=''; FLUSH PRIVILEGES; as the last step of your base image build so no shadowing row can ever appear.
  • Pin the auth plugin in your server config rather than inheriting the default - set default_authentication_plugin (MySQL 8.0) in my.cnf to the plugin your oldest client supports, so a new account never silently becomes unreachable.
  • Pass credentials through a login path file instead of flags or option files: mysql_config_editor set --login-path=local --host=localhost --user=root --password writes an obfuscated ~/.mylogin.cnf, then connect with mysql --login-path=local. No shell quoting, no plaintext password in ~/.my.cnf, nothing in shell history.
  • Add a connectivity smoke test to CI or your deploy pipeline that runs mysql --login-path=ci -e 'SELECT 1' against the real target. It catches a 1045 before application traffic does, and the exit code makes it a hard gate.
  • Set PASSWORD EXPIRE NEVER explicitly on service accounts, or monitor SELECT user, host, password_expired, account_locked FROM mysql.user from your alerting. Expiry-driven 1045s hit at 3 a.m. and look exactly like a credential leak.

Related Guides

Errors You Will Probably Hit Next

  • ERROR 1130 (HY000): Host 'x.x.x.x' is not allowed to connect to this MySQL server
  • ERROR 1044 (42000): Access denied for user 'appuser'@'localhost' to database 'appdb'
  • ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
  • ERROR 1698 (28000): Access denied for user 'root'@'localhost'

Treat 1045 as a report about which row the server matched, not about your password. The user and host printed in the message are the server's view of you, and they are the only facts in it - everything else is deliberately ambiguous. So the first move is always to get in by some other route and read mysql.user directly, because the error is designed to refuse to tell you whether the account, the host pattern, or the plugin was the problem. Password resets that appear to change nothing are the classic sign you are fixing a row the server never consults.

댓글

이 블로그의 인기 게시물

TypeError: Cannot read properties of undefined (reading 'map') - 11 Causes and Fixes

psql: FATAL: password authentication failed for user - 10 Causes and Fixes

Error: ERR_MODULE_NOT_FOUND: Cannot find package - 10 Causes and Fixes