Can’t connect to remote mysql server with php/apache but can through php/cli

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 has 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!

This entry was posted in Computing, Web Servers and tagged , , , , . Bookmark the permalink.
  • Guisomo

    thanks, this helped me a lot.!!!

  • steve

    SELinux is a security service that dictates access based on process (& others vars). Httpd = process & SELinux restricts it from accessing data outside (in this case) the DocumentRoot.

    Try from the command line:
    ‘getenforce’
    This tell you if SELinux is in permissive mode (warnings only) or enforcing mode (security on).

    Use command:
    ‘setenforce 1′ or ‘setenforce 0′
    To turn SELinux on or off, although this isn’t persistent – it’s only temporary.

    The /etc/SELinux/config file sets the default state of SELinux on boot.

    Now, to change the single directive of SELinux that controls this function:
    SELinux stores a list of boolean values as to what is/isnt allowed.
    In this case, we want to look into the httpd processes.

    Type in at the command prompt:
    ‘getsebool -a | grep httpd’ = 20 – 30 httpd related results.

    Read through the list, you’ll find ‘httpd_can_network_connect_db –> off’
    Here’s the culprit.

    Type in at the command prompt:
    ‘setsebool -P httpd_can_network_connect_db on’
    Using the -P flag will tell SELinux this is a persistent change.

    Hope this helps !!