php - How to connect to MySQL installed on Compute Engine from App Engine Standard?
one text
I want to migrate my website (PHP + MySQL) from shared hosting to Google Cloud.
My first attempt was to host the database on Google Cloud SQL and deploy the PHP code to the App Engine standard environment, I've tested it and it works perfectly, but that setup is way beyond my budget.
To reduce costs I have thought:
- Have the database on Compute Engine.
- Deploy PHP code to the App Engine standard environment
Regarding (1) I have installed MySQL on Compute Engine without any problem. From the console of my local device I have been able to enter MySQL, create a test database, create users, etc.
When I run gcloud compute instances list
I can see that the instance exists and is running:
NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS
mysql us-central1-a e2-micro N.NNN.N.N RUNNING
Regarding (2) I have created a minimal test setup. An app.yaml
file with the following content:
runtime: php81
# [START cloud_tasks_app_env_vars]
env: standard
# [END cloud_tasks_app_env_vars]
handlers:
# Serve your app through a front controller at index.php or public/index.php.
- url: .*
script: auto
And an index.php
file that tries to connect to the database in two ways.
Using localhost or the IP of the instance:
try {
$username = "root";
$password = "THEPASSWORD";
$dbName = "THEDATABASE";
/*
I tryed all these $host values
without success
*/
$host='INSTANCENAME';
$host='NN.NNN.N.N'; #Instance IP
$host='127.0.0.1';
$host='localhost';
$dsn = sprintf(
'mysql:dbname=%s;host=%s',
$dbName,
$host
);
$conn = new PDO(
$dsn,
$username,
$password
);
Using unix socket:
try {
$username = "root";
$password = "THEPASSWORD";
$dbName = "THEDATABASE";
$instanceUnixSocket = "/cloudsql/MYPROJECT:us-central1-a:INSTANCENAME";
$dsn = sprintf(
'mysql:dbname=%s;unix_socket=%s',
$dbName,
$instanceUnixSocket
);
// Connect to the database.
$conn = new PDO(
$dsn,
$username,
$password
);
In neither of the two cases the connection is possible, getting the error:
SQLSTATE[HY000] [2002] No such file or directory in /workspace/index.php:NN
Where NN
is the line where I declare the $dsn
variable.
IMPORTANT NOTE: The instance where I installed MySQL and App Engine are in the same project.
I want to know where is my error and how can I connect to MySQL like this.
I've searched the Google documentation and this site for a similar case, and I've seen two questions for which no satisfactory solution is given.
If there is a better way to achieve my purpose, I appreciate any guidance on that. It is not easy for a beginner in Google Cloud to decide on the most suitable tools.
Source