Transform Learning with a Powerful Enterprise LMS

Learn more
Moodle

Moodle "Database Connection Failed": Diagnosis and Fixes for Moodle 4.5 to 5.3

What "Error: Database connection failed" means in Moodle, how to find the real cause from the web server, the fix for each cause, and how to get alerted next time.

Learn more about this topic with AI

Gemini opens with the prompt copied - paste it into the chat to start.

Step path illustration for diagnosing a Moodle database connection failed error, from config.php values to the database server

"Error: Database connection failed" means Moodle could not open a connection to its database at the very start of the request, before it loaded any settings, so every page, login and CLI script fails the same way. The cause is almost always one of five things: the database server is down or unreachable, the credentials or host in config.php are wrong, the server has run out of connection slots, a socket, port or SSL setting does not match the server, or a connection pooler rejects Moodle's options. The fastest way to the real cause is to connect with the database's own client from the web server, using the exact values in config.php.

This guide follows the order we use on support calls for a Moodle database connection failed error: the problem, the symptoms, the causes ranked by likelihood, a diagnostic procedure, the fix for each cause, how to confirm the fix and how to prevent a repeat. Checked against the Moodle 5.3.0 source (lib/dmllib.php, the MySQL and PostgreSQL drivers, config-dist.php and the English error strings), October 2026. The same connection options exist on 4.5 LTS; on 5.1 and later config.php and the CLI scripts sit in the project root, not in public/.

The problem: what the error actually means

Every Moodle request loads config.php, which loads lib/setup.php, which calls setup_DB(). That function picks the driver from $CFG->dbtype and calls the driver's connect method with $CFG->dbhost, dbuser, dbpass, dbname, prefix and dboptions. If the database refuses or never answers, the driver throws a dml_connection_exception, which uses the language string dbconnectionfailed. Its full text is:

Error: Database connection failed. It is possible that the database is overloaded or otherwise not running properly. The site administrator should also check that the database details have been correctly specified in config.php

Because this happens before any settings are read from the database, nothing in Site administration can help: there is no admin page to log in to. Everything you change is in config.php, on the database server or in the network between them.

Symptoms and similar errors

  • Every page shows the same message, including the login page and /admin, for guests and logged-in users alike.
  • CLI scripts fail identically. php admin/cli/cron.php and admin/cli/checks.php load the same setup code, so cron stops at the same moment. Users later report missing emails and stuck tasks, which is a side effect, not a second fault.
  • It can be intermittent. A site that fails only at peak times, or only for some requests, usually has a connection limit or overload problem rather than wrong credentials.

Three neighbouring errors look similar but mean something else:

MessageWhat it means
Error: database driver problem detectedThe PHP extension for your database is missing, for example "PHP has not been properly configured with the MySQLi extension". Moodle never tried to connect.
Error reading from database / Error writing to databaseThe connection worked; a query failed. That is a schema, permission or SQL problem, not a connection problem.
A blank page or HTTP 500A PHP fatal error, often before Moodle's error handler is ready. Check the PHP-FPM or web server error log first.

Root causes, ranked by likelihood

This ranking reflects what we see most often on sites we support, not a survey.

RankCauseTypical trigger
1Database service stopped or unreachableServer reboot, out of memory kill, full disk, firewall or security group change
2Wrong host, name, user or password in config.phpServer migration, restored backup, password rotation, managed database endpoint changed
3Out of connection slotsTraffic peak, slow queries holding connections, more PHP workers than the database allows
4Socket, port or SSL mismatchlocalhost on MySQL uses a socket; a non-default port; a managed database that requires TLS
5Database user not allowed from this hostNew web server IP, MySQL grants tied to a host, PostgreSQL pg_hba.conf without a matching entry
6Connection pooler rejects options (PostgreSQL)PgBouncer or a similar pooler added in front of the database

Diagnostic procedure

Work through these steps in order. Each one rules out a row of the table.

  1. Read the exact message. If it says "database driver problem", go straight to the PHP extension fix below. If it says "Error reading from database", this is not a connection fault.
  2. Check the database service. On the database host run systemctl status mariadb, mysql or postgresql (the unit name varies by distribution), and check free disk space with df -h. On a managed service, check its console for status, maintenance events and storage.
  3. Copy the connection values from config.php: $CFG->dbtype, dbhost, dbname, dbuser, dbpass and the dboptions array (especially dbport, dbsocket, ssl and dbhandlesoptions).
  4. Connect from the web server with the database client, not from your laptop, using exactly those values:
    # MySQL or MariaDB
    mysql -h DBHOST -P 3306 -u DBUSER -p DBNAME
    
    # PostgreSQL
    psql "host=DBHOST port=5432 user=DBUSER dbname=DBNAME"
    The client prints the real reason: refused or timed out (service or network), access denied (credentials or host grants), unknown database, or too many connections.
  5. If the client works but Moodle fails, get Moodle's own driver message. Temporarily add $CFG->debug = (E_ALL); and $CFG->debugdisplay = 1; to config.php, then run sudo -u www-data php admin/cli/checks.php from the project root. With developer debugging on, the error is followed by a "Debug info" line holding the driver's message and error number. Remove both lines afterwards; config-dist.php marks them "NOT FOR PRODUCTION SERVERS".
  6. If it is intermittent, count connections. On MySQL or MariaDB compare SHOW GLOBAL STATUS LIKE 'Threads_connected'; with SHOW VARIABLES LIKE 'max_connections';. On PostgreSQL compare SELECT count(*) FROM pg_stat_activity; with SHOW max_connections;. Then check the database server log around the failure times.

Fixes for each cause

1. Database service stopped or unreachable

Start the service and find out why it stopped before you move on: the database log, the kernel log for out of memory kills, and disk usage on the data volume. If the database is on another host, test the port from the web server (for example nc -zv DBHOST 3306) and check firewalls and cloud security groups after any network change.

2. Wrong values in config.php

Correct dbhost, dbname, dbuser or dbpass so they match what worked in the client test. After a migration, confirm you edited the config.php the site actually loads; on 5.1 and later that is the one in the project root. A MySQL error 1045 means access denied for that user and password, and 1049 means the database name does not exist. On PostgreSQL the server says "password authentication failed for user" or that the database "does not exist".

3. Out of connection slots

MySQL and MariaDB return error 1040, "Too many connections". The fix is to make the numbers add up: the maximum number of PHP workers across all web nodes, plus cron and other clients, must fit under the database's max_connections with headroom. Raise the limit only if the database server has the memory for it, cap PHP-FPM workers, and find the slow queries that keep connections busy. config-dist.php describes 'dbpersist' => false as "the most stable setting", so leave persistent connections off unless you have measured a benefit. Our Moodle performance optimisation guide covers the caching and query work that reduces load.

4. Socket, port or SSL mismatch

  • MySQL and localhost: the comment in config-dist.php says MySQL "is always using socket if dbhost is 'localhost'" and to use 127.0.0.1 if you need a local TCP connection. If PHP's default socket path does not match the server's, either switch dbhost to 127.0.0.1 or set 'dbsocket' to the full socket path.
  • Port: when dbport is empty the MySQL driver uses PHP's mysqli.default_port or 3306, and the PostgreSQL driver uses 5432. Set 'dbport' if your server listens elsewhere.
  • TLS: managed databases often refuse plain connections. Set 'ssl' => 'require' or 'verify-full' in dboptions; prefer and disable are PostgreSQL only. An unknown value raises a different, explicit error naming the ssl option.

5. User not allowed from this host

MySQL accounts are defined per user and host, so a grant for the old web server address does not cover a new one. Create the account for the new host with the same privileges. On PostgreSQL, the message "no pg_hba.conf entry for host" means the server has no rule for that client address, user and database; add one and reload PostgreSQL.

6. PgBouncer or another pooler (PostgreSQL)

By default Moodle sends client_encoding=utf8 and standard_conforming_strings=on as startup options, which some poolers reject. Set 'dbhandlesoptions' => true and configure those two settings on the database or role instead. Moodle then checks them itself and fails with a clear message, for example "client_encoding = UTF8 not set" or "standard_conforming_strings = on, must be set at the database", and it refuses dbschema together with dbhandlesoptions. If the pooler runs in transaction mode, config-dist.php also says to set 'fetchbuffersize' => 0.

Missing PHP extension

If the message was "database driver problem", install and enable mysqli or pgsql for the PHP version the web server uses (PHP-FPM and CLI can load different php.ini files), then restart PHP-FPM.

Read replicas and other configurations

If you use read-only replicas through the readonly block in dboptions, a failed replica does not cause this error. The driver logs a debugging message such as "Readonly db connection failed for host" and carries on with the primary. Only a failure to reach the primary stops the site. Replicas default to a two-second connecttimeout; you can also set 'connecttimeout' for the primary so a dead database fails fast instead of tying up PHP workers.

A database that is too old for your Moodle release is a separate problem. It produces environment check failures during install or upgrade, not this message. Our Moodle hosting requirements article lists the supported database versions per branch.

Confirm the fix

  1. Load the front page and log in as an administrator.
  2. From the project root run sudo -u www-data php admin/cli/checks.php. It should run its checks instead of printing the connection error.
  3. Run cron once by hand, or wait a few minutes and check that the "Cron running" status recovers. If cron stays stuck, follow our Moodle cron not running guide.
  4. Remove any temporary debug lines from config.php.

Prevention

  • Get told first. Set $CFG->emailconnectionerrorsto in config.php. When a connection fails, Moodle emails that address with the error code, debug info and server name, at most once every ten minutes (it tracks this in an emailcount file in moodledata). It uses PHP's mail() directly, so the web server must be able to send mail, and $CFG->noemailever disables it.
  • Monitor the database itself: service up, disk space, connection count against max_connections, and slow queries.
  • Treat credentials as a change. Password rotations, host changes and new web nodes should include an update to config.php and the database grants, tested with the client before the switch.
  • Size connections deliberately whenever you add PHP workers or web nodes.

For the wider picture of how a Moodle site is laid out and run, see our Moodle guide.

How we can help

If your Moodle site is down with a connection error, or fails at peak times, we can find the cause and put monitoring in place so it does not happen again. See our LMS maintenance and support service and our Moodle development services, or get in touch through our contact page.

Frequently asked questions

What does "Error: Database connection failed" mean in Moodle?

Moodle could not open a connection to its database when the request started. The database may be down or overloaded, the details in config.php may be wrong, or the server may be refusing this client because of host rules, connection limits or TLS settings.

How do I see the real database error behind the Moodle message?

Connect with the database's own client from the web server using the values in config.php. Alternatively, temporarily set $CFG->debug = (E_ALL); and $CFG->debugdisplay = 1; in config.php and run php admin/cli/checks.php; the output then includes a Debug info line with the driver's message. Remove the debug lines afterwards.

Why does Moodle connect with 127.0.0.1 but not with localhost?

With MySQL and MariaDB, localhost always means a Unix socket connection. If PHP's default socket path differs from the server's, the connection fails. Use 127.0.0.1 for TCP, or set 'dbsocket' in dboptions to the correct socket path.

Can Moodle email me when the database connection fails?

Yes. Set $CFG->emailconnectionerrorsto to an address in config.php. Moodle sends a warning with the error code and debug info through PHP's mail(), at most once every ten minutes, unless $CFG->noemailever is set.

Does a failed read replica cause this error?

No. If a read-only replica configured in dboptions cannot be reached, Moodle logs a debugging message and uses the primary database. The error appears only when the primary connection fails.

Free 30-minute consultation

Not sure where to start? Talk to an LMS engineer.

Tell us what platform you run and what you need. You’ll get honest, practical advice - even if the answer is that you don’t need us.

Sources & references

  1. lib/dmllib.php: setup_DB() and dml_connection_exception (Moodle 5.3.0) - Moodle HQ
  2. config-dist.php: database setup and dboptions (Moodle 5.3.0) - Moodle HQ
  3. lang/en/error.php: dbconnectionfailed string (Moodle 5.3.0) - Moodle HQ
  4. PostgreSQL driver: pgsql_native_moodle_database.php (Moodle 5.3.0) - Moodle HQ
  5. Client Authentication Problems - PostgreSQL Global Development Group
  6. Server Error Message Reference - Oracle (MySQL)
Add as a preferred source on Google

Add All-in-One LMS as a preferred source to see more of our articles in Google’s Top Stories.

Learn more about this topic with AI

Gemini opens with the prompt copied - paste it into the chat to start.

Keep reading

Step path illustration for diagnosing a Moodle cron that is not running, from the status check to fixing the crontab and stuck tasks

· 11 min read

Moodle Cron Not Running: Diagnosis and Fixes

Why Moodle cron stops, how to diagnose it from the status check and a manual run of admin/cli/cron.php, the fix for each cause, and how to confirm an…

Illustration of five ranked cards with the top card starred, representing a Moodle theme comparison for institutions in 2027

· 15 min read

Moodle Themes for 2027, Ranked for Institutions

Eleven free and premium Moodle themes scored for universities, colleges and training providers on 5.3 LTS readiness, upgrade safety, accessibility, b…

Before you go - get a free LMS audit

Tell us which LMS you use and what is not working. An engineer replies within one business day.

Choose which optional cookies we may use. You can change this at any time from "Cookie preferences" in the footer. Cookie policy · Privacy policy