Matt Button

Apache can't connect to remote MySQL server, but scripts can

Today at work we were migrating some sites to a new server infrastructure with the different services (i.e. php, mysql, mail) spread over different servers. One problem we ran into whilst setting this up was that php scripts running through apache were having trouble connecting to the mysql server.

What was even stranger though, was the fact that this problem only appeared when the php script(s) were run through apache - running them through the command line / shell worked absolutely fine. After a couple of hours of debugging, head bashing and confusion we found the solution at the bottom of one of those very very long experts exchange threads.

It turns out that some linux distros have a neat little access control system called SELinux which was blocking communication by apache to remote database servers. The aforementioned exchange thread suggests disabling SELinux entirely by executing

sudo setenforce 0

but this isn’t a permanent solution and won’t persist through a reboot without changing a config file.

This can be accomplished by changing a line in /etc/selinux/config.

Change the line that says: SELINUX=enforcing to SELINUX=disabled

However, if you’re willing to do a bit of digging there are SEL options you can change to grant apache access to remote database servers, and if you have a few hours to kill, there’s also the fedora documentation. Hopefully this’ll save someone else the headache we had!