"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.phpandadmin/cli/checks.phpload 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:
| Message | What it means |
|---|---|
| Error: database driver problem detected | The 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 database | The connection worked; a query failed. That is a schema, permission or SQL problem, not a connection problem. |
| A blank page or HTTP 500 | A 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.
| Rank | Cause | Typical trigger |
|---|---|---|
| 1 | Database service stopped or unreachable | Server reboot, out of memory kill, full disk, firewall or security group change |
| 2 | Wrong host, name, user or password in config.php | Server migration, restored backup, password rotation, managed database endpoint changed |
| 3 | Out of connection slots | Traffic peak, slow queries holding connections, more PHP workers than the database allows |
| 4 | Socket, port or SSL mismatch | localhost on MySQL uses a socket; a non-default port; a managed database that requires TLS |
| 5 | Database user not allowed from this host | New web server IP, MySQL grants tied to a host, PostgreSQL pg_hba.conf without a matching entry |
| 6 | Connection 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.
- 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.
- Check the database service. On the database host run
systemctl status mariadb,mysqlorpostgresql(the unit name varies by distribution), and check free disk space withdf -h. On a managed service, check its console for status, maintenance events and storage. - Copy the connection values from
config.php:$CFG->dbtype,dbhost,dbname,dbuser,dbpassand thedboptionsarray (especiallydbport,dbsocket,sslanddbhandlesoptions). - Connect from the web server with the database client, not from your laptop, using exactly those values:
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.# MySQL or MariaDB mysql -h DBHOST -P 3306 -u DBUSER -p DBNAME # PostgreSQL psql "host=DBHOST port=5432 user=DBUSER dbname=DBNAME" - If the client works but Moodle fails, get Moodle's own driver message. Temporarily add
$CFG->debug = (E_ALL);and$CFG->debugdisplay = 1;toconfig.php, then runsudo -u www-data php admin/cli/checks.phpfrom 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.phpmarks them "NOT FOR PRODUCTION SERVERS". - If it is intermittent, count connections. On MySQL or MariaDB compare
SHOW GLOBAL STATUS LIKE 'Threads_connected';withSHOW VARIABLES LIKE 'max_connections';. On PostgreSQL compareSELECT count(*) FROM pg_stat_activity;withSHOW 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.phpsays MySQL "is always using socket if dbhost is 'localhost'" and to use127.0.0.1if you need a local TCP connection. If PHP's default socket path does not match the server's, either switchdbhostto127.0.0.1or set'dbsocket'to the full socket path. - Port: when
dbportis empty the MySQL driver uses PHP'smysqli.default_portor 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'indboptions;preferanddisableare PostgreSQL only. An unknown value raises a different, explicit error naming thessloption.
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
- Load the front page and log in as an administrator.
- 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. - 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.
- Remove any temporary debug lines from
config.php.
Prevention
- Get told first. Set
$CFG->emailconnectionerrorstoinconfig.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 anemailcountfile in moodledata). It uses PHP'smail()directly, so the web server must be able to send mail, and$CFG->noemaileverdisables 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.phpand 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
- lib/dmllib.php: setup_DB() and dml_connection_exception (Moodle 5.3.0) - Moodle HQ
- config-dist.php: database setup and dboptions (Moodle 5.3.0) - Moodle HQ
- lang/en/error.php: dbconnectionfailed string (Moodle 5.3.0) - Moodle HQ
- PostgreSQL driver: pgsql_native_moodle_database.php (Moodle 5.3.0) - Moodle HQ
- Client Authentication Problems - PostgreSQL Global Development Group
- Server Error Message Reference - Oracle (MySQL)
Learn more about this topic with AI
Gemini opens with the prompt copied - paste it into the chat to start.