postgresql connection failure:SQLSTATE[08006] [7] could not connect to server: Permission denied Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?

PHP 程序无法连接到 CentOS 上的PostgreSQL,但是在 CentOS 服务器上却能正常运行 psql,

操作如下:多次重启 PG 数据库后发现 CGI 脚本无法连接数据库,但是可以使用 psql 连接上数据库

PHP 程序报错如下:

PostgreSQL server: could not connect to server: Permission denied Is the server running on host "localhost" (127.0.0.1) 
and accepting TCP/IP connections on port 5432?

 

网上查了很多文章,发现是SELinux(Linux上的强制访问控制安全模块)惹得祸,很想关闭它,

但是据说他是系统被攻破后的最后一道防线,那就暂时记录此类问题的解决方案,以后有时间的话,好好研究一下这个SELinux!

 

此问题的原因是SELinux阻止httpd进程--httpd_can_network_connect_db 连接数据库--不管是哪种类型的数据库

所以需要确保设置正确的布尔值以允许Web应用程序与数据库通信,使用setsebool命令改变该布尔变量的状态,从而使得httpd进程能够访问数据库服务器:

sudo setsebool -P httpd_can_network_connect_db 1

 

改变成功后,可以使用getsebool命令进行查看:

/usr/sbin/getsebool httpd_can_network_connect_db

 

 

查看 SELinux 设置的所有 Booleans 值

getsebool -a

 

 

上述状态改变只是暂时性的,一旦系统重启,该变量状态将改变回初始状态,因此,可以使用如下命令永久性改变状态:

/usr/sbin/setsebool -P httpd_can_network_connect_db on

 


如需关闭SELinux则可以执行以下操作
修改/etc/selinux/config SELINUX=enforcing 为 SELINUX=disabled

 

参考链接:

https://stackoverflow.com/questions/27749691/php-cant-connect-to-postgresql-on-centos-7

https://unix.stackexchange.com/questions/8854/how-do-i-configure-selinux-to-allow-outbound-connections-from-a-cgi-script

关于 SELinux  的参考链接:

https://wiki.centos.org/TipsAndTricks/SelinuxBooleans#line-44

http://www.blogjava.net/ycyk168/archive/2012/09/09/387340.html

posted @ 2018-10-29 00:52  Ryan_zheng  阅读(6159)  评论(0编辑  收藏  举报