Management Guides Troubleshooting

Error Establishing a Database Connection in WordPress: VPS Fix

What causes "Error establishing a database connection" on a self-managed VPS, how to find which cause you have in a few commands, and how to stop it coming back.

"Error establishing a database connection" means PHP is running and WordPress loaded far enough to read wp-config.php, but it could not log in to MariaDB or MySQL. On a VPS the most common reason is that the database server is not running, usually because the kernel killed it when the server ran out of memory, or because the disk is full.

The fix is to find out which of a handful of causes applies, in the order below. Start the database if it is stopped, read why it stopped, and only then look at credentials, the host setting and damaged tables.

The commands below follow the official MariaDB, WordPress and WP-CLI documentation. They were not run on a test server for this article.

Causes at a glance

What you seeLikely causeWhere to look
Whole site and wp-admin show the error; systemctl status mariadb says inactive or failedDatabase server stopped, often killed for memoryKernel journal, free -h
Database will not start, or stops again at onceDisk fulldf -h
ERROR 1045 Access denied or ERROR 1049 Unknown database from the clientWrong user, password or database name in wp-config.phpwp-config.php, database accounts
ERROR 2002 Can't connect ... through socket while the server is runningWrong DB_HOST, or socket path mismatchDB_HOST, socket path
Error comes and goes under loadToo many connections, or memory pressureMax_used_connections, journal
Front end works partly; wp-admin says tables are unavailable and may need repairCrashed tableswp db check

Check that the database server is running

sudo systemctl status mariadb      # MariaDB on all distributions
sudo systemctl status mysql        # MySQL on Ubuntu, Debian
sudo systemctl status mysqld       # MySQL on AlmaLinux, Rocky Linux

If it is not active, find the reason before starting it. The OOM killer is the part of the Linux kernel that ends a process when memory runs out, and the database is usually the largest process on a small server. It leaves a line in the kernel log:

sudo journalctl -k --since "2 days ago" | grep -i -E "out of memory|oom-kill"
sudo journalctl -u mariadb -n 50 --no-pager
free -h

A line such as Out of memory: Killed process 1234 (mariadbd) confirms it. Start the service again and confirm it stays up:

sudo systemctl start mariadb
sudo systemctl is-active mariadb

The site works again, and it will fail again at the next memory peak unless you fix the cause. The OOM killer guide covers adding swap and finding what uses the memory; the last section of this article lists the WordPress-specific settings.

Check the disk

df -h
df -i

MariaDB needs free space for its logs and temporary tables. With a filesystem at 100% it refuses to start or stops accepting writes. Free space first, following "No space left on device", then start the database and read the last lines of its journal for table errors.

Test the credentials from wp-config.php

Print the four settings WordPress uses:

grep -E "DB_(NAME|USER|PASSWORD|HOST)" /var/www/example.com/wp-config.php

Then connect with exactly those values using the command-line client. It prints the real error that WordPress hides:

mariadb -u WPUSER -p -h localhost WPDB -e "SELECT 1;"   # use mysql instead of mariadb on a MySQL server

If the client connects, the credentials are right. WP-CLI runs the same test with the values it reads from wp-config.php and then checks every table:

cd /var/www/example.com
sudo -u www-data wp db check       # the web user is nginx or apache on AlmaLinux, Rocky Linux

"Access denied" means the user or password is wrong. This is common after a migration, where the file came from the old server and the account did not. Set the password to match the file, then test again:

sudo mariadb -e "ALTER USER 'WPUSER'@'localhost' IDENTIFIED BY 'the-password-from-wp-config';"
sudo -u www-data wp db check

"Unknown database" means DB_NAME does not exist; sudo mariadb -e "SHOW DATABASES;" lists the names that do.

localhost and 127.0.0.1 are not the same

With DB_HOST set to localhost, PHP connects through a Unix socket, which is a file on disk. With 127.0.0.1 it connects over TCP on port 3306. Each can fail while the other works.

  • Socket path mismatch. The server creates its socket at /run/mysqld/mysqld.sock on Ubuntu and Debian and /var/lib/mysql/mysql.sock on AlmaLinux and Rocky Linux. If PHP looks elsewhere, name the path in the host setting: define( 'DB_HOST', 'localhost:/run/mysqld/mysqld.sock' );.
  • TCP refused. 127.0.0.1 fails when the server has networking turned off (skip-networking) or listens on another address. Check with sudo ss -tlnp | grep 3306.

Find the socket the server is using with sudo mariadb -e "SHOW VARIABLES LIKE 'socket';", change DB_HOST if needed, and run wp db check again.

Too many connections

Every PHP request that touches the database holds one connection. When more requests arrive than max_connections allows (the default is 151), new ones are refused with "Too many connections" and WordPress shows the same generic error. Compare the limit with the highest number reached since the server started:

sudo mariadb -e "SHOW VARIABLES LIKE 'max_connections'; SHOW GLOBAL STATUS LIKE 'Max_used_connections';"

If the two numbers are equal, the limit was hit. Raising it costs memory, so first ask why so many were open at once: slow queries holding connections, a traffic burst that page caching would absorb, or more PHP-FPM workers than the database can serve. As a rule of thumb, keep the total of pm.max_children across all pools below max_connections; see PHP-FPM tuning. To change the limit, set max_connections under [mysqld] in /etc/mysql/mariadb.conf.d/50-server.cnf (Ubuntu, Debian) or /etc/my.cnf.d/mariadb-server.cnf (AlmaLinux, Rocky Linux), restart the service and run the query above again.

Crashed tables

After a hard stop, such as an OOM kill, a full disk or a power loss on the host, a table can be marked as crashed. The front end may still load while wp-admin reports that one or more database tables are unavailable.

sudo -u www-data wp db check
sudo -u www-data wp db repair

Take a dump before repairing if the server lets you: wp db export /root/before-repair.sql. Repair applies to MyISAM and Aria tables. InnoDB, the default engine, answers that it does not support repair; it recovers by itself when the server restarts, and if it cannot, the reason is in journalctl -u mariadb.

Without WP-CLI, WordPress has a built-in repair page. Add define( 'WP_ALLOW_REPAIR', true ); to wp-config.php and open /wp-admin/maint/repair.php. The page works without logging in, so remove the line as soon as you are done.

When the error is intermittent

An error that appears for a minute and disappears is nearly always resources. Either the database was killed and systemd started it again, which shows in journalctl -u mariadb as repeated start messages, or the connection limit was reached during a burst. Check both as shown above, and look at what ran at that time: a backup, a cron job, or a crawler.

WordPress in Docker

In a Compose setup the database is another container, so localhost is wrong: it points at the WordPress container itself. The host must be the service name from the Compose file, for example WORDPRESS_DB_HOST: db.

The second Docker cause is timing. On first start the database container needs time to initialise, and WordPress may try to connect before it is ready. Check the state and the log:

docker compose ps
docker compose logs --tail=50 db

If the database is still starting, wait and reload. To make the order permanent, give the database service a health check and let WordPress wait for it with depends_on and condition: service_healthy. The full file is in WordPress with Docker Compose.

Stop it from recurring

  • Give the database a memory budget. innodb_buffer_pool_size (default 128M) plus the PHP-FPM workers must fit in RAM with room to spare. How much RAM WordPress needs has the arithmetic.
  • Limit PHP-FPM. Too many workers is the usual reason the kernel runs out of memory and picks the database as the process to kill.
  • Add swap on servers with little RAM, so that a short peak slows the server down without killing anything.
  • Check that systemd restarts the service. systemctl show mariadb -p Restart prints the policy. If it is no, add Restart=on-failure under [Service] with sudo systemctl edit mariadb.
  • Watch disk usage, and cache pages so that most visits never open a database connection.
Share story:

Continue reading other guides on How VPS.