LogCure.com
Server Error

How to Resolve "Error Establishing a Database Connection" on Apache/Nginx

What Causes "Error Establishing a Database Connection"?

This error means your web application (WordPress, Laravel, custom PHP, etc.) successfully received an HTTP request but could not open a socket to the database server. The three most common causes are: wrong database credentials in the config file, the MySQL/MariaDB service has crashed or stopped, or the database itself has a corrupted table that prevents connections from completing authentication.

Quick Diagnostic Table

ScenarioCauseFix
Error on all pagesMySQL service stoppedsudo systemctl restart mysql
Error after password changeWrong DB credentials in configUpdate wp-config.php / .env
Error on specific site onlyWrong DB_HOST or DB_NAMEVerify config file values
Error after server crashCorrupted InnoDB tablesRun mysqlcheck --repair
Too many connections errorMySQL max_connections hitIncrease max_connections in my.cnf

How to Fix the Database Connection Error

Fix 1 — Verify Database Credentials

Open your config file and cross-check every value:

DB_HOST is almost always localhost or 127.0.0.1 unless your DB is on a remote server.

Fix 2 — Check and Restart MySQL

  1. Check status: sudo systemctl status mysql
  2. If inactive: sudo systemctl start mysql
  3. If it fails to start, check: sudo journalctl -u mysql -n 50

Fix 3 — Test the Connection via CLI

Run this command to test your credentials directly: mysql -u your_db_user -p -h localhost your_db_name. If this fails with "Access denied," your password is wrong. If it shows "Can't connect to server," MySQL is not running.

Fix 4 — Repair Corrupted Tables

Run the MySQL repair utility: sudo mysqlcheck --repair --all-databases -u root -p. This fixes InnoDB and MyISAM table corruption that commonly occurs after unclean server shutdowns.

Fix 5 — Check MySQL Error Log

Inspect /var/log/mysql/error.log for the root cause. Look for InnoDB corruption messages, out-of-disk-space errors, or authentication plugin failures. Address the specific error found.

Verification

✓ How to Confirm the Fix Worked

Reload the website. For WordPress, the "Error Establishing a Database Connection" banner will be replaced by your site. For Laravel, run php artisan migrate:status — a successful DB connection will list your migrations. Monitor MySQL uptime with mysqladmin -u root -p status.