"Error establishing a database connection" means WordPress loaded but could not reach its MySQL or MariaDB database, so no page renders. The cause is almost always one of five things: wrong credentials, a stopped database server, a wrong host, corrupted tables, or the database being out of connections or memory. The database itself tells you which. This guide covers each cause, managed cloud databases, and the case where the error stays stuck in a cache after the database is fixed, plus the other "site looks down but is fine" lockout: briefly unavailable for scheduled maintenance.
The message means exactly what it says. Every page shows it, including /wp-admin, because nothing renders without the database. (One useful exception: if WordPress can connect but a table is corrupted, the front end still shows this error while /wp-admin shows a different message about tables needing repair, which points you straight at corrupted tables.) The message is otherwise the same no matter why the connection failed, which is why people thrash around editing random files. Do not. The real cause is almost always one of five things, and the database itself will tell you which one if you ask it directly.
First, find out which failure it is
Before you change anything, test the connection the way WordPress does, straight from the command line, and read the error code. Use the same credentials that are in wp-config.php:
mysql -h DB_HOST -u DB_USER -p DB_NAME -e 'SELECT 1'The number it returns is the whole diagnosis:

| What you see | What it means | Go to |
|---|---|---|
ERROR 1045 ... Access denied | Wrong user or password | Credentials |
ERROR 2003 ... (111) (refused) | Server down, or wrong DB_HOST / port | Server down |
ERROR 2003 ... (110) (timed out) | A firewall or security group is dropping the connection | Cloud databases |
ERROR 2005 ... Unknown server host | DB_HOST is a typo, or DNS cannot resolve it | Credentials |
ERROR 1040 ... Too many connections | The server is up but out of connection slots | Too many connections |
ERROR 144 / 145 / "marked as crashed" | A table is corrupted | Corrupted tables |
This works the same against MySQL or MariaDB; the error numbers are identical. If the command succeeds and returns 1, the connection details themselves are valid (SELECT 1 proves the login and database selection worked, though not that every table is intact). The problem is then one of two things: wp-config.php is pointing WordPress at a different database than the one you just tested, or a stale copy of the error is stuck in a cache (see the cached-error case below).
One thing that will not help, despite being all over the internet: raising the PHP memory limit. A database connection failure is a credentials or networking problem, not a memory one, so leave WP_MEMORY_LIMIT out of it.
No shell access? Run the same test from a browser. Put this in a file like db-test.php in your site root, copy the four values from wp-config.php, load the file once, and then delete it (it prints your database error and must not stay public):
<?php
// db-test.php: fill in your wp-config values, load in a browser, then delete this file.
$link = @mysqli_connect( 'DB_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME' );
echo $link
? 'OK: connected.'
: 'FAILED (' . mysqli_connect_errno() . '): ' . mysqli_connect_error();The number in FAILED (1045) is the same error code as the table above, so the diagnosis is identical whether you use the command line or the browser.
Cause 1: Wrong database credentials
This is the most common one, and the fix is direct: if the mysql test returns ERROR 1045, the username or password is wrong, so reset it and update wp-config.php to match. WordPress reads four constants from wp-config.php; check what they actually are:

// wp-config.php
define( 'DB_NAME', 'your_database' );
define( 'DB_USER', 'your_user' );
define( 'DB_PASSWORD', 'your_password' );
define( 'DB_HOST', 'localhost' );A few things that quietly break this:
- A rotated or mistyped password. Paste the exact
DB_PASSWORDinto themysqltest above. If you getERROR 1045, the password (or user) is wrong, full stop. Reset it in your host's control panel or withALTER USER 'your_user'@'host' IDENTIFIED BY 'new_password';and updatewp-config.phpto match. - An unescaped quote or backslash in the password.
DB_PASSWORDis a single-quoted PHP string, so a literal'has to be written\'and a literal\written\\. A$or a backtick is safe inside single quotes, but an unescaped quote breaks the line entirely. If in doubt, regenerate a password without quotes or backslashes. DB_HOSTis not alwayslocalhost.localhostconnects over a Unix socket;127.0.0.1forces TCP; a remote or managed database needshostname:portorhostname:/path/to/socket. Some hosts use a non-localhost value likemysql.yourhost.com. If you migrated the site, this is the field that is most often stale.
After a migration, also confirm the database actually exists on the new server and the user has rights to it: SHOW DATABASES; and SHOW GRANTS FOR 'your_user'@'host';.
On cPanel hosting you do the same checks in the GUI: MySQL Databases shows the database name and lets you reset the user's password (then update DB_PASSWORD to match), and phpMyAdmin confirms the database and its tables are actually there. The cause is identical; only the tooling differs.
Cause 2: The database server is down
If the test returns ERROR 2003 ... (111), the host is reachable but nothing is answering on the database port. Usually the MySQL or MariaDB service has stopped. Check it and start it:
systemctl status mysql # or: systemctl status mariadb
sudo systemctl start mysqlIf it refuses to start, read the log (/var/log/mysql/error.log or journalctl -u mysql). The most common reason a database will not start, by a wide margin, is a full disk. MySQL cannot write its files and dies on boot. Check with df -h; if the data partition is at 100%, clear space (old logs, backups, the binary logs under the data directory) and start the service again. A close second is a crash that left the data directory needing recovery, which the error log will spell out.
On shared hosting you cannot restart the service yourself. A 2003/refused error there means the host's database server is down or overloaded, and the fix is a support ticket, not a config edit.
Cause 3: Too many connections
ERROR 1040 (HY000): Too many connections means the server is healthy but every connection slot is in use, so WordPress is turned away. MySQL allows max_connections clients at once (151 by default), plus one reserved slot for an admin.
The quick way to breathe is to restart the database, which drops every stuck connection. That clears the symptom but not the cause. What actually fills the slots:
- A traffic spike (real visitors, or a bot crawl) beyond what the server is sized for.
- Slow queries holding connections open. One missing index on a busy query can pin connections for seconds each, and they stack up.
- A plugin or a bad bit of code opening connections without closing them.
Look at what is actually connected with SHOW PROCESSLIST; (or SHOW FULL PROCESSLIST;). If you see dozens of identical queries in Sending data, that query is your problem; fix the query or add the index. If the list is full of connections from one plugin that never closes them, isolate it: rename wp-content/plugins to plugins.off to disable everything at once, confirm the connection count drops, then move plugins back one at a time until the culprit reappears. If the box genuinely needs more headroom and has the RAM for it, raise the limit:
SET GLOBAL max_connections = 300; -- until restartMake it permanent in my.cnf under [mysqld], but only raise it if the server has the memory; every connection costs RAM, and setting it too high just trades one crash for another.
Cause 4: Corrupted database tables
If the error mentions a specific table being "marked as crashed" or you see ERROR 144/145, a table is corrupted, usually after an unclean shutdown or a disk problem. WordPress has a built-in repair tool. Add this to wp-config.php, just above the "That's all, stop editing" line:
define( 'WP_ALLOW_REPAIR', true );Then visit https://yoursite.com/wp-admin/maint/repair.php directly. It does not require a login (that is the point, since you are locked out), and it offers "Repair Database" and "Repair and Optimize Database." Run it, then remove that line from wp-config.php immediately, because leaving the repair page open to the public is a real risk.
From the command line, the equivalent is:
wp db repair # WP-CLI
# or, against the server directly (one database, then widen if needed):
mysqlcheck -u DB_USER -p --auto-repair DB_NAMEOn cPanel, repair without touching files: in phpMyAdmin, open the database, tick all tables, and choose Repair table from the "With selected" dropdown; some hosts also expose a "Repair Database" button in cPanel itself.
If repair cannot fix it, restoring the affected table (or the whole database) from your last good backup is the reliable path. This is the moment you find out whether your backups actually work.
Managed and cloud databases (AWS RDS, Google Cloud SQL)
When the database is a managed service (Amazon RDS, Aurora, Google Cloud SQL, Azure Database) and the app is on a separate server, the failure mode shifts from "the database is broken" to "the network between them is blocked." The tell is the OS code inside the 2003 error:

A timed-out (110) connection to a cloud database is almost never the database itself. It is the network path. The usual suspects:
- Security group / firewall rules. The RDS instance's security group must allow inbound
3306from the web server's security group or IP. This is the number-one cause of a brand-new RDS connection timing out. On Google Cloud SQL the equivalent is authorized networks (for public IP) or running the Cloud SQL Auth Proxy / using a private IP inside the VPC. - Public versus private IP. If your app connects over a private IP, it has to be in the same VPC (or a peered one). Pointing
DB_HOSTat a private endpoint from outside the VPC just times out. - The instance is stopped or in maintenance. RDS instances can be stopped manually (and auto-start after 7 days), and an instance that filled its storage goes into a
storage-fullstate and stops accepting writes. Check the instance status in the console. - A stale endpoint. If you restored from a snapshot or recreated the instance, the endpoint hostname changed. The old
DB_HOSTinwp-config.phpnow points at nothing. (A plain reboot or a Multi-AZ failover keeps the same endpoint, so those do not cause this.) max_connectionsis set by instance size. On RDS the default is derived from the instance class memory, not 151, and you change it through the parameter group, notmy.cnf. A small instance under load hits1040quickly.- TLS required, or rotated credentials. If the instance requires TLS, a non-TLS session is rejected during the handshake (you get an SSL or authentication error from MySQL, not a port-refused timeout). And if credentials live in Secrets Manager or you use IAM authentication, a rotation the app did not pick up looks exactly like a wrong password.
So on cloud: a 1045 is still credentials, a 1040 is still connection limits (sized by your tier), but a timeout points you at security groups and networking, not at WordPress.
Fixed it but the error won't go away?
If the connection test above returns 1 (the database is healthy) yet visitors still see the error, the database is not your problem anymore: a stale copy of the error page is stuck in a cache and is being served after recovery. That happens when the error came back as an HTTP 200 and a page cache, server cache, or CDN stored it. It is a distinct problem with a distinct fix, covered in full in the next section. The short version is to purge the cache and make your wp-content/db-error.php return a 503 so it can never be cached again.
Database connection error stuck in cache
If your database recovered but the site still shows "Error establishing a database connection," the error page is stuck in a cache, and the fix is one file: make wp-content/db-error.php return a 503 status with a Cache-Control: no-store header. Clearing your browser cache does nothing, because the stale page is not in your browser. It is in a cache between you and WordPress, and it got there because the error response came back as an ordinary HTTP 200 OK with no cache-control headers, which is exactly what a cache is built to keep.
Confirm it is a cached error
Request the page and read the status line:
curl -sI https://example.com/ | grep -i 'http\|cache'HTTP/1.1 500or503means the database is failing live. That is a real outage; go back to the error code table.HTTP/1.1 200 OKon a page that still shows the error means the database is fine and a cache is serving you a stored error.
A private window will not help, because the copy lives upstream. Purge in this order and re-test after each step: your page-cache plugin (WP Super Cache, W3TC, WP Rocket, LiteSpeed), then the server cache (Varnish, nginx fastcgi_cache), then the CDN (Cloudflare and similar).
Why a custom db-error.php gets cached
A cache stores a response when the status is one it considers cacheable (a 200 OK is the obvious one) and nothing in the headers tells it not to. Modern WordPress core gets this right on its own: with no custom error page, it renders its built-in "Database Error" screen with a 500 status and aggressive no-cache headers.

That is deliberate. The WordPress reference for dead_db() says the DB error "sets the HTTP status header to 500 to try to prevent search engines from caching the message. Custom DB messages should do the same." The moment you drop in a custom wp-content/db-error.php (the on-brand "we will be right back" page every tutorial tells you to add), core loads your file and gets out of the way:
// wp-includes/class-wpdb.php: what core does when the DB is unreachable
if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
require_once WP_CONTENT_DIR . '/db-error.php';
die();
}It does not set a status code for you, and PHP's default is 200 OK. So a custom error page that never calls http_response_code() ships a friendly maintenance screen with a 200 on it. I reproduced this with a stock WordPress behind Varnish, the friendly db-error.php installed, the database stopped for one request:

The first request is a MISS that stores the 200 error. After the database is back, the next request is a HIT serving the cached error from a perfectly healthy origin.
This is not a caching-plugin bug. A page-cache plugin (WP Super Cache, W3 Total Cache, WP Rocket, LiteSpeed Cache) will not cache a connect-time database failure, because dead_db() runs before WordPress fires init, so the plugin never arms its caching for that request. The layer that stores the bad copy is almost always an HTTP-level cache that only sees status and headers: Varnish, an nginx fastcgi_cache, or a CDN with full-page caching turned on.
The fix: make db-error.php return 503
Break both conditions at once: an error status the cache will not store, plus a no-store header. A 503 Service Unavailable with Retry-After tells crawlers and uptime monitors the outage is temporary. Replace wp-content/db-error.php with this:
<?php
// wp-content/db-error.php
// Served automatically by WordPress when the database is unreachable.
// The status and the no-store header together tell every cache layer not to keep this.
http_response_code( 503 );
header( 'Retry-After: 30' );
header( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0' );
?><!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>We will be right back</title></head>
<body style="font-family:sans-serif;text-align:center;padding-top:15%">
<h1>We will be right back</h1>
<p>The site is briefly unavailable. Please try again in a moment.</p>
</body>
</html>
Every request during the outage is now a MISS, and the moment the database recovers the next request is the real page. There is an SEO reason too: a cached 200 error can be indexed as your homepage or flagged as a soft 404, while a 503 with Retry-After tells search engines to come back.
If you do not need a branded page at all, delete wp-content/db-error.php entirely. With no drop-in, core handles the outage itself with a 500 and no-store headers, which is already cache-safe.
Then purge the copy you already poisoned, or the old 200 keeps serving until it expires. Run the delete from your WordPress root so a mis-paste cannot match the wrong path:
# WP Super Cache / on-disk page cache, run from your WordPress root
cd /var/www/html && rm -rf wp-content/cache/supercache/*
# Cloudflare: purge just the affected URL (least privilege beats purge_everything)
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CF_TOKEN" \
-H "Content-Type: application/json" \
--data '{"files":["https://example.com/"]}'Keep errors out of every cache layer
The 503 drop-in protects every layer at once, but custom cache configurations can override the defaults:
- Page-cache plugins. None will keep a
503. Where the stuck copy lives: WP Super Cache underwp-content/cache/supercache/(Settings > WP Super Cache > Delete Cache); W3 Total Cache in disk-enhanced mode underwp-content/cache/page_enhanced/(Performance > Purge All Caches); WP Rocket from the admin bar or Settings > WP Rocket > Clear Cache; LiteSpeed Cache at the server level, so purge through Toolbox > Purge All. Leave any "cache 404s and other non-200responses" option off. - nginx
fastcgi_cache/proxy_cache. Cache only successful and redirect responses, and keep error codes out offastcgi_cache_use_stale, or nginx will deliberately serve a stale error during a backend hiccup:
# Cache 200/301/302 for a while; do not hold onto errors.
fastcgi_cache_valid 200 301 302 10m;
fastcgi_cache_valid 500 502 503 504 0;- Varnish. The built-in VCL already declines
no-storeresponses and does not treat a503as cacheable. People break this with a customvcl_backend_responsethat force-sets a TTL on everything, so gate on the status explicitly:
sub vcl_backend_response {
if ( beresp.status >= 500 ) {
set beresp.uncacheable = true;
return (deliver);
}
set beresp.ttl = 1h;
}
- Cloudflare and other CDNs. Cloudflare does not cache HTML by default; you are exposed only with a "Cache Everything" rule or APO. Even then it respects origin
Cache-Controland does not cache5xxby default, unless an Edge Cache TTL or status-code Cache Rule assigns a TTL to errors, or "Origin Cache Control" is turned off. "Always Online" is the opposite, useful feature: it serves the last known-good copy while the origin is down.
A dead Redis or Memcached object cache
A persistent object cache fails differently. If a wp-content/object-cache.php drop-in loses its Redis or Memcached backend, it usually throws later in the request, after init, and WordPress ends with wp_die(). By then the page-cache plugin is armed, so unlike the database case a page cache can store the result. The message is usually "Error establishing a Redis connection." The fix follows the same principle: make the failure return a non-200 status with no-store. Most Redis drop-ins can be configured to fail with a 500; if yours cannot, the status-aware cache rules above are your backstop.
The 503 page stops a blip from being immortalized, but it does nothing about the cause. Once the site is back, check max_connections against real concurrency, look for an OOM-killed database with dmesg -T | grep -i oom, and check whether deploys restart MySQL, since that restart window is exactly when an uncached request can capture the error. If the real symptom is a site stuck on "briefly unavailable for scheduled maintenance," that is the .maintenance drop-in, covered below.
Briefly unavailable for scheduled maintenance
If every page, /wp-admin included, shows "Briefly unavailable for scheduled maintenance. Check back in a minute." instead of a database error, the database is not involved. Delete the .maintenance file in the site root and the site comes back immediately:
rm /var/www/html/.maintenanceWordPress writes that dotfile at the start of every core, plugin or theme update, with one line of PHP setting $upgrading to the current Unix timestamp, and removes it when the update finishes. On every request wp_maintenance() calls wp_is_maintenance_mode(), which reads the file; if it exists and the timestamp is less than 10 minutes old, WordPress prints the unstyled maintenance message and exits. An interrupted update (a PHP timeout, a fatal error, a tab closed mid-upgrade, a host killing the process) never reaches the line that deletes it.
That 600-second window is why the message sometimes "clears itself": the marker goes stale, but the file is still on disk and the next update overwrites it with a fresh timestamp. Delete it. Because it is a dotfile, a plain ls hides it:
ls -la /var/www/html/.maintenance-rw-r--r-- 1 www-data www-data 26 Mar 30 09:12 /var/www/html/.maintenance
The site root is wherever wp-config.php and wp-load.php live (/var/www/html on a stock box, often ~/public_html or ~/htdocs on managed hosting). Without SSH, delete it over SFTP or the host's file manager, after turning on hidden files: in FileZilla it is Server, Force showing hidden files; in cPanel File Manager it is the Settings toggle for "Show Hidden Files (dotfiles)."
Finish the update and stop it recurring
The leftover file means an update died partway, so the files and database schema may be out of step. Re-run it from WP-CLI, which does not depend on a browser tab staying open:
wp core update
wp plugin update --all
wp theme update --allIf wp core update says you are already current but the site behaves oddly, wp core update --force refreshes the files. Then fix whatever killed the update:
| Cause | Symptom | Fix |
|---|---|---|
PHP max_execution_time too low | Large update times out mid-write | Raise to 120s+ in php.ini or via host panel |
| Memory exhaustion | White screen during update, then stuck | Raise WP_MEMORY_LIMIT / PHP memory_limit |
| Updating many items at once | Bulk plugin update dies on one item | Update plugins one at a time |
| Closed the tab mid-update | Browser-driven update never finished | Let updates run to completion |
| Disk full | Update can't write, leaves marker | Free space, then delete .maintenance |
Maintenance mode on purpose, and a branded page
For deliberate maintenance before manual database or file work, WP-CLI writes and removes the same marker:
wp maintenance-mode activate
wp maintenance-mode status
wp maintenance-mode deactivateTo brand the page, drop a maintenance.php into wp-content/; wp_maintenance() loads WP_CONTENT_DIR/maintenance.php before falling back to the one-liner. Keep the 503 so crawlers treat the outage as temporary (the default maintenance response already sends a 503, so a briefly stuck file is not an SEO problem unless it stays for days):
<?php
http_response_code(503);
header('Retry-After: 600');
?>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Updating</title></head>
<body>
<h1>Applying updates</h1>
<p>The site will be back in a minute. Thanks for your patience.</p>
</body>
</html>Stop it happening again
Two things cause almost every one of these outages, and both are silent until they take the site down: the database server running out of disk, and the connection count reaching max_connections. Alert on both. Once the site is back, a few habits keep this from recurring:
- Watch the two things that actually cause it: free disk on the database server, and connection count against
max_connections. Both are trivial to alert on, and both are silent until they take the site down. - Size the database for real traffic. Most "too many connections" outages are an undersized instance plus one slow query. Find the slow query.
- Make outages cache-safe. A
wp-content/db-error.phpthat returns a503(see the cached-error fix) means a brief database blip never gets immortalized in a cache. - Test your backups. Corruption and a full disk are the two cases where a working restore is the only real fix. A backup you have never restored is a guess.
wp-config.php, the database server being down, hitting the max_connections limit, corrupted tables, or (on a managed database) a firewall blocking the connection.wp-config.php: mysql -h DB_HOST -u DB_USER -p DB_NAME -e 'SELECT 1'. The error number tells you the cause: 1045 is wrong credentials, 2003 (111) is a stopped server or wrong host/port, 2003 (110) is a firewall timeout, 1040 is too many connections, and a "marked as crashed" message is a corrupted table.wp-content/db-error.php return a 503 so it cannot be cached again. Full details in the cached database error section.dead_db() before the init hook fires, so WP Super Cache never reaches the stage where it would write a cache file. The layer that stores a cached error is almost always an HTTP-level cache, such as Varnish, an nginx fastcgi_cache, or a CDN with full-page caching enabled. A dead Redis object cache that throws after init is the exception.Cache-Control: no-store. WordPress core uses 500 for its built-in message. I prefer 503 Service Unavailable with a Retry-After header for a custom page, because it describes a temporary outage and tells crawlers to come back.Cache-Control and does not cache 5xx responses, so a db-error.php that returns 503 with no-store stays out of the edge.wp-config.php, wp-admin/ and wp-content/, hidden because of the leading dot (use ls -la or show hidden files in FTP). Deleting it is safe: it is a transient marker that only says an update is in progress. Its presence means an update was interrupted, so re-run that update afterwards..maintenance is more than 600 seconds old, because wp_is_maintenance_mode() treats it as stale. The file stays on disk, though, and the next update refreshes it, so delete it rather than waiting.DB_PASSWORD in wp-config.php to match, confirm the database name matches DB_NAME, and repair tables from phpMyAdmin (open the database, tick all tables, choose Repair table). The db-test.php snippet above gives you the same error number as the command line, so you can still diagnose the cause from a browser.Sources
Authoritative references this article was fact-checked against.
- Common WordPress errors, WordPress.org documentationwordpress.org
- Editing wp-config.php, WordPress.org documentationwordpress.org
- MySQL client error reference (1045, 1040, 2002, 2003)dev.mysql.com
- Troubleshoot connecting to an Amazon RDS instance, AWSrepost.aws
- Connect to Cloud SQL for MySQL, Google Cloud documentationcloud.google.com
- dead_db(): WordPress Developer Referencedeveloper.wordpress.org
- 503 Service Unavailable, MDNdeveloper.mozilla.org
- Default cache behavior, Cloudflare docsdevelopers.cloudflare.com
- ngx_http_fastcgi_module (fastcgi_cache_valid): nginx docsnginx.org
- Varnish built-in VCL, Varnish documentationvarnish-cache.org
- HTTP 503: the SEO-safe way to take a site down, Yoastyoast.com
- wp_maintenance(): WordPress Developer Referencedeveloper.wordpress.org
- wp_is_maintenance_mode(): WordPress Developer Referencedeveloper.wordpress.org
- wp maintenance-mode: WP-CLI Command Referencedeveloper.wordpress.org





