This can happen for a number of reasons but usually when the db gets overloaded or experiences a lot of slow queries. Because the database is either shutdown or thinking too hard, WordPress was not able to make a new connection.
To fix the slow queries get a plugin like Query Monitor to identify slow query pages. Always look for ways to reduce database calls. Double check your 404 page and make sure it doesn’t have to think too hard. If someone is looking for exploits on your site then they usually blast a bunch of known plugin locations. When they don’t find any all those requests will turn into 404 pages so make that page as fast a possible.
Add caching to reduce server queries or configure your server to use Varnish so it doesn’t have to think at all in most cases.
Ultimately, just restart it before it becomes a problem. Set up a crontab or cron job somewhere to trigger a restart every day or x hours. You’ll be less likely to see the full error message.
If you’re stuck with this problem then consider making a custom page for when that error occurs — so when it does happen it looks a little better than ‘error establishing connection’.
Make a static page and place it at wp-content/db-error.php
. When the connection fails it will load that page. That could also be an opportunity to trigger a restart from PHP so you don’t have to do it manually.