SELinux causes PHP to connect to MySQL exception Can 't connect to MySQL server

  • 2020-06-23 02:07:29
  • OfStack

Colleagues reported a strange phenomenon that the simplest test PHP code was normal in the test environment, but in the formal environment, tcp/ip, unix socket could not connect to mysql in any way.

I helped check it, and it is true. Whether it is IP, tcp/ip connection with port, or unix socket connection, the error message is similar:

Could not connect: Can't connect to MySQL server on 'MYSQL.SERVER' (13)

There is no way to modify MySQL's authorization, or adjust php.ini's Settings for MySQL, or modify MySQL's listening port.

If the command line is used to manually connect to MySQL, then 1 cut is normal.

The problem looks like php(with apache) is not allowed to connect to MySQL, but the firewall is not restricted either. In retrospect, the SELinux factor was the only one that caused the problem.

getsebool -a|grep -i httpd

You can see that the httpd process license mode is set here. If you look more closely, there is one option:

getsebool -a|grep -i httpd_can_network_connect
httpd_can_network_connect --> off

It turns out that SELinux restricted httpd's access to the outside world. Just turn it on:
setsebool -P httpd_can_network_connect=1

If you are not familiar with SELinux, you can also directly modify the system configuration file /etc/sysconfig/selinux to close globally:

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
# Change Settings to disabled
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     mls - Multi Level Security protection.

Then restart the operating system to take effect.
Or, directly execute the command, which can take effect online:

[root@imysql~]# setenforce 0
setenforce: SELinux is disabled

Related articles: