2
votes

I have a Google Cloud PostgreSQL instance. I can connect to it by several local IP addresses, after having whitelisted them in the connections tab on GCP. I developed my application and now, when I try to connect the instance from production webserver, it says:

Fatal error: Uncaught PDOException: SQLSTATE[08006] [7] could not connect to server: Connection timed out Is the server running on host "34.65.215.xx" and accepting TCP/IP connections on port 5432?

the PHP I'm using is:

$wpdb2 = new PDO('pgsql:host=34.65.215.xx;port=5432;dbname=xxxxx', 'postgres', 'xxxxxx');

I wrote to my webserver support and they answered me by opening the 5432 port in output on the 34.65.215.xx IP. After that I still can't connect to the instance.

The strace says:

0.000120 socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 4
0.000043 setsockopt(4, SOL_TCP, TCP_NODELAY, [1], 4) = 0
0.000031 fcntl(4, F_SETFL, O_RDONLY|O_NONBLOCK) = 0
0.000024 fcntl(4, F_SETFD, FD_CLOEXEC) = 0
0.000027 connect(4, {sa_family=AF_INET, sin_port=htons(5432), sin_addr=inet_addr("34.65.215.xx")}, 16) = -1 EINPROGRESS (Operation now in progress)
0.000112 poll([{fd=4, events=POLLOUT|POLLERR}], 1, 30000) = 1 ([{fd=4, revents=POLLOUT|POLLERR|POLLHUP}])
15.270417 getsockopt(4, SOL_SOCKET, SO_ERROR, [110], [4]) = 0
0.000103 close(4) = 0

I just don't know what to do next...

Can someone help to understand?

3

3 Answers

2
votes

As everybody recommends, you may check your public IP address of your webserver. To know it you can use the webpage provided by @kurtisvg or from a linux terminal you can use this:

$ curl ifconfig.co

Also, if your webserver OS is Red Hat or any fork (CentOS, Scientific Linux, etc) you should configure SELinux boolean httpd_can_network_connect_db changing it to 1 to connect your PHP app to any database in another server.

$ sudo setsebool -P httpd_can_network_connect_db 1

Everything should be working fine now so try to connect again your PHP app to your Cloud SQL instance.

0
votes

If my understanding is correct:

  • you have a Cloud SQL instance on public IP 34.65.215.xx
  • you have a PHP script running on a webserver hosted outside of GCP

I can connect to it by several local IP addresses, after having whitelisted them in the connections tab on GCP

Did you add your webserver host IP in the Cloud SQL IP whitelist?

Suggestion

Did you consider running your workload on GCP? AppEngine for example. You will be able to enforce the security.

Because in this design, it's not really a good practice, and security level is very low.

Latency between backend server and database could be also an issue.

0
votes

Check to make sure your current IP address is whitelisted for your instance. IP addresses can change periodically. You can check your public ip by visiting a tool like https://whatismyipaddress.com/.

If you want a more secure way to connect without having to whitelist your IP, consider using the Cloud SQL Proxy.