This error “Error Establishing a Database Connection” will happen on Cloudways hosting if the memory usage on the server is too high and it’s running out of RAM.
You’ll see this in particular on their smaller $10 and $20/month servers which typically will have 1-2gb of RAM and in some cases no swap file configured or only a 1gb swap file configured.
When all the RAM is used and the swap space fills up the server is essentially out of memory and some of the services including SQL server will crash and hence the website throws at database error.
How To Fix It
The fix is quite simple:
Step 1: Diagnose the problem and see what memory usage looks like
Log into the site via SSH or console and run the command “htop” – this will give you realtime CPU and memory usage on the server something like below
This server above only has 1gb of RAM (964mb) of which 771mb is currently used – you’ll see this on the “mem” line.
It has a 1gb swap file of which 577mb is currently used, the SWP line.
CPU usage is also at 100%
This server is essentially at capacity and is getting this error. Watching it for 5 minutes or so there’s several instances where RAM is 100% usage (964mb of 964mb) and the swap file is full (1024mb of 1024mb)
When this happens the site starts throwing database errors.
Step 2: Fix the problem by adding more swap disk, reducing memory pressure or upgrading the server
In some cases some Cloudways servers have no swap space and this will almost always lead to issues. You’ll need to speak to Cloudways support to get this fixed – some of their support agents will push back on the request but it’s ridiculous to run a web server without swap disk.
If you have a swap disk of 1gb increasing this to 2 or 4gb will help but the server will probably be slow if RAM usage is hitting 100% on a regular basis – swap disk uses the hard drive as memory which is much slower than RAM.
Dialing down PHP memory usage can help and setting it to 128mb or 192mb will relieve memory pressure as will running wp-cron from the cron scheduling and disabling the inbuilt wpcron.
Ultimately if RAM is being 100% usage then upgrading the server to provide more available working memory is the only solution that will fully resolve the problem.