The Problem
WordPress cannot connect to the MySQL database because the socket path in wp-config.php does not match the actual MySQL socket location on the server. This is common on custom server setups, cPanel servers, and managed hosting.
Symptoms
- "Error establishing a database connection" on the site
- wp-admin shows the same error
- MySQL service is running and accessible from command line
- Database credentials are correct
- Other applications on the same server can connect to MySQL
Real Error Message
``` Error establishing a database connection
This either means that the username and password information in your wp-config.php file is incorrect or we can't contact the database server at localhost. ```
Common Cause: Socket Path Mismatch
```php // wp-config.php (DEFAULT) define('DB_HOST', 'localhost');
// MySQL is actually listening on a custom socket // /var/run/mysqld/mysqld.sock or /var/lib/mysql/mysql.sock ```
When DB_HOST is set to localhost, MySQL tries to connect via the default socket. If MySQL uses a custom socket path, the connection fails.
How to Fix It
Fix 1: Find the Actual MySQL Socket Path
```bash # Find the MySQL socket path mysql -u root -p -e "SHOW VARIABLES LIKE 'socket';"
# Or check MySQL config grep socket /etc/mysql/my.cnf grep socket /etc/my.cnf
# Or find the socket file find /var/run /var/lib /tmp -name "*.sock" 2>/dev/null
# Common paths: # /var/run/mysqld/mysqld.sock (Ubuntu/Debian) # /var/lib/mysql/mysql.sock (CentOS/RHEL) # /tmp/mysql.sock (macOS with Homebrew) # /opt/lampp/var/mysql/mysql.sock (XAMPP) ```
Fix 2: Update wp-config.php with Socket Path
```php // wp-config.php define('DB_HOST', 'localhost:/var/run/mysqld/mysqld.sock');
// Alternative format for some hosts: define('DB_HOST', '127.0.0.1'); // Force TCP instead of socket ```
Fix 3: Use TCP Connection Instead of Socket
// Force TCP connection by using 127.0.0.1 instead of localhost
define('DB_HOST', '127.0.0.1');When using 127.0.0.1, MySQL connects via TCP/IP instead of the Unix socket, bypassing the socket path issue entirely.
Fix 4: Create a Symlink to the Socket
```bash # If MySQL uses /var/lib/mysql/mysql.sock but WordPress expects # /var/run/mysqld/mysqld.sock, create a symlink:
sudo mkdir -p /var/run/mysqld sudo ln -s /var/lib/mysql/mysql.sock /var/run/mysqld/mysqld.sock sudo chown mysql:mysql /var/run/mysqld/mysqld.sock ```
Fix 5: Verify MySQL is Running
```bash # Check MySQL status sudo systemctl status mysql # or sudo systemctl status mariadb
# Test connection with WordPress credentials mysql -u wordpress_user -p wordpress_database -h 127.0.0.1
# Check MySQL port netstat -tlnp | grep 3306 ```
Fix 6: Enable WordPress Database Debugging
```php // wp-config.php define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); define('SAVEQUERIES', true);
// Then check /wp-content/debug.log for detailed errors ```