Why php pdo connection to google cloud mysql instance using public ip fails with getaddrinfo failed: Name or service not known?

19 views Asked by At

I have a google cloud platform mysql instance (say m1) with both private and public IP. I want to connect to the database using PHP PDO from a local machine (say m2) over the internet. I have authorized the IP of m2 in m1's public network. I am able to connect to the MySQL db@m1 from m2 and create tables using mysql client from bash.

$rr@m2:~ mysql -h public_ip_of_m1 -u root -p mypass

This is successful.

However, from the same machine when connecting from a PHP application

<?php
 try {
$dbhost = '35.x.x.x';
$dbuser = 'root';
$dbpass = 'xxxx';
$dbase = 'xxxx';

$connConfig = [
    PDO::ATTR_TIMEOUT => 5,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]; 

$conn = new PDO('mysql:host=$dbhost; dbname=$dbase', $dbuser, $dbpass, $connConfig);
}catch (PDOException $e){
 echo "Error!: " . $e->getMessage() . "<br/>";
 die();
 }
 
 ?>

fails and shows Error!: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known.

I have not used "Cloud SQL Auth proxy". Is it absolutely required even for connecting from local applications to public IP over the internet? I certainly did not feel so from the docs. Would anyone please point out what is going wrong here? Thank you.

0

There are 0 answers