PHP - Connection failed to PostgreSQL database in virtual machine

3

I am trying to connect to a PostgreSQL database in a virtual machine, through a php script, but being unsuccessful.

I execute the php from the host (Windows 8.1) and the postgresql is at the virtual machine (Debian 8.6). I use VirtualBox.

The error output from the browser is:

Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on host "10.0.2.15" and accepting TCP/IP connections on port 5432? in C:\xampp\htdocs\pg_test.php on line 11

with line 11 being pg_connect($conn_string).

The parameters passed to pg_connect($conn_string)are:

$host = "host=10.0.2.15";
$port = "port=5432";
$dbname = "dbname=postgres";
$user = "user=user_switch";
$password = "password=switch";
$conn_string = "$host $port $dbname $user $password";
pg_connect($conn_string);

I use host=10.0.2.15 because I checked (with ifconfig) that the guest has the ip 10.0.2.15.

I modified the files pg_hba.conf and postgresql.conf, to include the lines:

pg_hba.conf:

host all all 0.0.0.0/0 trust

postgresql.conf:

listen_addresses = '*'

In iptables I added the rule -A INPUT -p tcp -m cp --dport 5432 -j ACCEPT

I also tried by disabling the firewall on the Windows host.

In some places they say its SELinux blocking the connection, but I don't have it installed in the guest.

I am able to succesfully connect to the database using the user "user_switch" in the guest with the command psql -d postgres -U user_switch -W -h localhost, in which it prompts me for the password.

Thanks in advance, please feel free to ask about more specifications I may have forgotten.

php
apache
postgresql
virtual-machine
asked on Stack Overflow Oct 12, 2016 by LeonMarchetti

1 Answer

2

Host and guest must be on the same network. You have to assign proper address to both, for example 192.168.56.1 on host and 192.168.56.101 on guest. For security reasons, you should remove the line allowing connection from any IP (0.0.0.0/0) and add the following line to pg_hba.conf:

host  all  all  192.168.56.0/24  trust

and restart PostgreSQL. This allows any connection attempt to guest from 192.168.56.x.

answered on Stack Overflow Oct 12, 2016 by pietrop • edited Oct 13, 2016 by pietrop

User contributions licensed under CC BY-SA 3.0