PHP cant connect to postgreSQL in Centos 7 Selinux

centos7PHPpostgresqlselinux

After migration to a new VPS and trying website on new server(Centos 7), Selinux somehow prevents http from accessing Postgresql:

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

and yes my postgresql in on port 6432 because of pgbouncer that we use to reduce server load. I googled around and find out it's because of Selinux so I used selinux commands to allow httpd connection to db setsebool -P httpd_can_network_connect_db on and it works as in when I look in Selinux config with sestatus -b it's turned ON but the problem still exists…

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

Funny thing is I know it's because of Selinux cause when I use setenforce 0 It works and connect to postgresql without any problem.
what should I do?

Best Answer

I found the solution with help of a Bogdan Kuštan. It because Selinux accepts 5432 as Postgresql port and does not work with other ports. You can check acceptable ports to Selinux labeld port with semanage port -l command. You can add ports to labeled ports with "semanage port -a" command with some other parameters and in my case:

semanage port -a -t postgresql_port_t -p tcp 6432