SQLSTATE[HY000] [2003] Can't connect to MySQL server

A while ago I was in a project which had separate CentOS web server and database servers. I had whitelisted the IP addresses we were using so the machines could reach each other, but all other connections were dropped. One would expect that to be enough, but my requests returned me ‘SQLSTATE[HY000] [2003] Can’t connect to MySQL server’. Apparently SE Linux didn’t want me to connect yet.

How can it be? Did I misconfigure the firewall?

In short: no I didn’t. I wrote a script which was using PDO for its database connection from PHP to MySQL. At first the script was working and connecting fine. After accessing a web page that was using the script, the error appeared. At first I thought a configuration error in the firewall had to be the issue. While thinking back of what I did there was one difference: I tested the script on the command line. On the CLI the script worked, so I assumed the script to be working in a web environment as well. However, this is a different sapi!
It took me a while to find out that the problem was caused by SE Linux. I searched for a while before finding this post: https://www.drupal.org/node/1124234
It refers to this article: http://googolflex.com/?p=482

Solving it

In short: SE Linux is blocking network connections.

Please don’t

The author of the googolflex blog set

SELINUX=enforcing

to

SELINUX=disabled

in 

/etc/selinux/config 

or to issue a command 

sudo setenforce 0

Please do

However, I would advice to not disable SE Linux and just issue the commands
setsebool httpd_can_network_connect_db 1
setsebool -P httpd_can_network_connect 1
Disabling SE Linux should be your last resort, not your first.

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *