PHP Warning: mysql_connect(): Can’t connect to MySQL server on… (13)
I created some barebones Fedora servers that I’m intending to create a load balanced cluster from using Apache’s mod_proxy_balancer. My topology will eventually look like this:
load_balancer -> (ws1, ws2, ws3) -> mysql_server
As you can see, it’s nothing fancy. To test the balancer, each web server has a PHP script that connects to the MySQL database and inserts its hostname and IP address. Then I could run a simple query to determine whether the balancer was distributing the load according to my rules.
The PHP script was basic too:
$dbhost = "mysql.host.com"; $dbuser = "testuser"; $dbpass = "testpass"; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (mysql_error()); $dbname = "testdb"; mysql_select_db($dbname); $query = "INSERT INTO testtable(ip, host) VALUES('" . $_SERVER["SERVER_ADDR"] . "', '" . $_SERVER["SERVER_NAME"] . "');"; print $query; mysql_query($query); mysql_close($conn);
I’ve done this a thousand times, so you can imagine my frustration at getting this error message:
[Mon Feb 01 16:22:21 2010] [error] [client 192.168.1.1] PHP Warning: mysql_connect() [<a href='function.mysql-connect'>function.mysql-connect</a>]: Can't connect to MySQL server on 'mysql.host.com' (13) in /var/www/html/index.php on line 7
I spent almost 2 hours looking for various solutions. I’ll list the most common ones in case you’re searching for a solution and mine doesn’t work for you:
–Ensure that MySQL user permissions are configured correctly.
–Ensure that MySQL is running on the server and on the correct port
–Ensure that selinux is not blocking the MySQL port or the mysqld process
These three items can be tested by simply logging into MySQL from a remote host using the following command:
mysql -u testuser -p -h mysql.host.com testdb
If that gives you a MySQL prompt, you can rule out the above three causes.
Some of the less obvious suggestions, which didn’t solve my problem either were:
–Ensure MySQL is using the correct path to the mysql.sock in my.ini
–Ensure that the server wasn’t started with –skip-networking
Though I tried a number of configuration changes for both MySQL, the server MySQL was running on (including disabling selinux completely), and PHP, I failed to overlook that selinux was blocking Apache’s outgoing connections to the MySQL database.
So what finally solved my problem was disabling selinux completely on the server Apache was running on. I should have done this in the first place, as I normally do with my Linux desktop installations.
This can be accomplished by changing a line in /etc/selinux/config. Change the line that says:
If you do some searching you can find out how to add an exception for Apache, after 2 hours I didn’t feel like fussing with those.