Tuesday, April 30, 2024

WordPress网站出现Error establishing a database connection

WordPress网站出现Error establishing a database connection(建立数据库连接时出错),查看发现Apache状态正常,而MySQL/MariaDB服务已经停止运行,重启服务器或者用service mysqld restart命令(MySQL数据库)或者systemctl restart mariadb.service命令(MariaDB数据库)可以暂时解决问题,过一段时间还会出现。

查看/etc/my.cnf,找到MySQL/MariaDB错误日志的位置(比如log-error=/var/log/mariadb/mariadb.log),查看日志,发现了很多处[ERROR] mysqld: Out of memory。

分析原因应该是Apache2在网站访问高峰时占用内存过高,MySQL/MariaDB因运行内存不足,会自动退出所致。

解决方法:
1、将Apache2换成Nginx或其他轻量级Web服务器。
2、不想更换Apache2的可以增大服务器物理内存或添加Swap交换文件。
3、不想更换Apache2也不想增加服务器物理内存,且网站访问量不大,可以尝试修改Apache2配置文件(文件路径/etc/httpd/conf/httpd.conf)。Apache2目前有三种稳定的MPM(Multi-Processing Module,多进程处理模块)模式,分别是prefork,worker和event。(查看Apache2的MPM模式,可以使用httpd -V命令。)

编辑/etc/httpd/conf/httpd.conf文件,添加下面内容:

<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
ServerLimit 100
MaxRequestWorkers 100
MaxConnectionsPerChild 2000
</IfModule>

说明:

<IfModule mpm_prefork_module>
StartServers 5 #推荐设置:小=默认 中=20~50 大=50~100
MinSpareServers 5 #推荐设置:与StartServers保持一致
MaxSpareServers 10 #推荐设置:小=20 中=30~80 大=80~120
ServerLimit 150 #推荐设置:小=500 中=500~1500 大型=1500~3000
MaxRequestWorkers 150 #推荐设置:小=500 中=500~1500 大型=1500~3000
MaxRequestsPerChild 0 #推荐设置:小=10000 中或大=10000~500000
</IfModule>

备注:在Apache2.3.13以前的版本MaxRequestWorkers被称为MaxClients。此外,设置ServerLimit参数最好与MaxRequestWorkers的值保持一致。

One comment

  1. 其实nginx也会出现这种情况,结果发现是数据库挂了

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.