Blog / Linux/ Fix WordPress "Error Establishing a Database Connection" on LNMP Servers

Fix WordPress "Error Establishing a Database Connection" on LNMP Servers

lnmp服务器WordPress网站出现“建立数据库连接时出错”mysql自动关闭了

Problem Description

Your WordPress site displays the error "Error establishing a database connection." This typically occurs when the MySQL database service stops unexpectedly.

Solution Overview

You can create a monitoring script that periodically checks the MySQL service status and automatically restarts it if found stopped. Follow the steps below.

1. Create the Monitoring Script

Use a text editor (e.g., vi) to create a script file:

vi /root/tools/mysql_check.sh

Copy and paste the following script content:

#!/bin/bash

# Check if mysqld process exists
pgrep -x mysqld &> /dev/null

if [ $? -ne 0 ]
then
    # Log and start MySQL service
    echo "At time: `date` : MySQL is stopped, restarting." >> /home/wwwlogs/mysql_messages
    service mysql start
else
    # Optional: log running status (comment out in production to reduce logs)
    # echo "MySQL server is running."
    :
fi

After saving and exiting, make the script executable:

chmod +x /root/tools/mysql_check.sh

2. Configure a Cron Job

Edit the current user's cron jobs:

crontab -e

Add the following line to run the script every 5 minutes:

*/5 * * * * /bin/bash /root/tools/mysql_check.sh

Save and exit. The cron job will take effect automatically.

Additional Notes & Recommendations

  • Script Path: Ensure the path /root/tools/mysql_check.sh is correct and the script has execute permissions.
  • Service Start Command: The example uses service mysql start. Depending on your system, you might need systemctl start mysqld or /etc/init.d/mysql start. Adjust accordingly.
  • Log File: The script logs stop/restart times to /home/wwwlogs/mysql_messages. Ensure the directory exists and is writable.
  • Root Cause: This is a temporary workaround. Frequent MySQL crashes often indicate deeper issues like insufficient memory, misconfiguration, attacks, or problematic queries. After implementing monitoring, check MySQL error logs (usually /var/log/mysql/error.log or /var/log/mysqld.log) to identify and fix the underlying cause.
  • Security: The script is stored in /root/. Manage permissions carefully, especially on multi-user servers.

Post a Comment

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