连接虚拟机中的PostgreSQL数据库失败


PHP - Connection failed to PostgreSQL database in virtual machine

我试图通过php脚本连接到虚拟机中的PostgreSQL数据库,但不成功。

我从主机(Windows 8.1)执行php,而postgresql在虚拟机(Debian 8.6)。我用VirtualBox

浏览器的错误输出是:

警告:pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection timed out (0x0000274C/10060)服务器运行在主机"10.0.2.15"上并在端口5432上接受TCP/IP连接吗?C:'xampp'htdocs'pg_test.php on line 11

,第11行为pg_connect($conn_string)

传递给pg_connect($conn_string)的参数有:

$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);

我使用host=10.0.2.15,因为我检查了(使用ifconfig)来宾有ip 10.0.2.15

我修改了文件pg_hba.confpostgresql.conf,包括以下行:

pg_hba.conf:

host all all 0.0.0.0/0 trust

postgresql.conf:

listen_addresses = '*'

iptables中我添加了规则-A INPUT -p tcp -m cp --dport 5432 -j ACCEPT

我也试过在Windows主机上禁用防火墙。

在某些地方,他们说SELinux阻塞了连接,但我没有在客户端安装它。

我能够在客户机中使用命令psql -d postgres -U user_switch -W -h localhost使用用户"user_switch"成功连接到数据库,其中它提示我输入密码。

提前感谢,请随时询问我可能忘记的更多规格

主机和来宾必须在同一网络中。您必须为两者分配适当的地址,例如主机上的192.168.56.1和来宾上的192.168.56.101。出于安全考虑,您应该删除允许从任何IP (0.0.0.0/0)连接的行,并将以下行添加到pg_hba.conf:

host  all  all  192.168.56.0/24  trust

并重启PostgreSQL。这允许任何连接尝试从192.168.56.x guest。