How to connect to Google cloud SQL instance using php?-ThrowExceptions

Exception or error:

With the following code am able to connect to my SQL instance from localhost environment , but when i upload the same code to my VM instance and try to connect it from there am getting “connection failed: connection timed out”

Note: I added VM instance’s External IP address in Authorized network section.

<?php
$servername = "SQL INSTANCE IP ADDRESS : port";
$username = "root";
$password = "password";
$dbname="appdb";

$response=array();

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

Please help, Thanks.

How to solve:

If you have your PHP outside of GCP (compute VM, App Engine, etc) You can either Install the cloud proxy in your app server and your app would connect like if the DB was in localhost, or you can use the public IP settings (I would suggest using the Proxy this way you don’t have to use attach a public IP to your SQL instance)

If the PHP app is hosted in GCP you may follow the steps for the service where your app is

Answer´╝Ü

How to connect from Compute Engine to Cloud SQL internal ip address (PHP)

Your Compute Engine instance must be in the same region as your Cloud
SQL instance, and on the network configured for a private connection

1.Create the Cloud SQL instance with internal ip address . Create a user, password and database.

2.Getting started with PHP on Compute Engine

After you copied the startup-script.sh runt this command to create the instance:

 gcloud compute instances create $MY_INSTANCE_NAME \
--image-family=ubuntu-1804-lts \
--image-project=ubuntu-os-cloud \
--machine-type=g1-small \
--scopes userinfo-email,cloud-platform,sql-admin  \
--metadata-from-file startup-script=scripts/startup-script.sh \
--zone $ZONE \
--tags http-server

On the scopes we added sql-admin, then create the firewall rule.

3.SSH to the instance you just created.

4.Install mysql. You could add this part to the startup script.

 sudo apt install mysql-client-core-5.7

5.Test if you can connect to SQL instance using internal ip address.

mysql --host=internall-ip-sql  --user=test --password

6.If you are able to connect then :

cd /opt/app/routes
sudo nano web.php

7.Add your code to router->get('/', function (Request $request)

8.In the browser go to http://compute-engine-instance-externall-ip

Success!

Leave a Reply

Your email address will not be published. Required fields are marked *