''No such file or directory' when connecting to MySQL Server in Google App Engine in PHP

I am trying to connect to my Google Cloud SQL instance with PHP (I am using PDO). When running my PHP file (from in the Google Cloud terminal), I receive the following error:

Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory in /home/bob_brown_the_dev/index.php:17
Stack trace:
#0 /home/bob_brown_the_dev/index.php(17): PDO->__construct('mysql:dbname=ma...', 'root', '', NULL)
#1 {main}
  thrown in /home/bob_brown_the_dev/index.php on line 17

This is what my PHP file looks like:

<?php

$username = 'root';
$password = getenv("MYSQL_PASS");
$dbName = 'main';
$connectionName = getenv("INSTANCE_CONNECTION_NAME");
$socketDir = getenv('DB_SOCKET_DIR') ?: '/cloudsql';

$dsn = sprintf(
    'mysql:dbname=%s;unix_socket=%s/%s',
    $dbName,
    $socketDir,
    $connectionName
);

// Connect to the database.
$conn = new PDO($dsn, $username, $password, $conn_config);

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

echo "Connected successfully";

?>

And this is what my app.yaml file looks like:

runtime: php73

entrypoint:
  serve index.php

env_variables:
  APP_DEBUG: true
  LOG_CHANNEL: stderr
  APP_STORAGE: /tmp
  INSTANCE_CONNECTION_NAME: "<instance-id>:us-west2:<name>"
  DB_SOCKET_DIR: "/cloudsql/<instance-id>:us-west2:<name>"
  MYSQL_PASS: <password>
  DB_CONNECTION: mysql

beta_settings:
    cloud_sql_instances: "<instance-id>:us-west2:<name>"

Thanks in advance for any help!

EDIT:

It appears there was a problem when I fetched the environmental variables. Once I fixed that problem, the error changed to:

Uncaught PDOException: SQLSTATE[HY000] [2002] Not a directory in /home/bob_brown_the_dev/index.php:17
Stack trace:
#0 /home/bob_brown_the_dev/index.php(17): PDO->__construct('mysql:host=loca...', '...', '...')
#1 {main}
  thrown in /home/bob_brown_the_dev/index.php on line 17

This is what the DSN looks like when I return it:

mysql:dbname=main;unix_socket=/cloudsql/<name>:us-west2:<other name>/<name>:us-west2:<other name>


Solution 1:[1]

If you're running your app in Cloud Shell, then you'll need to start the Cloud SQL Auth Proxy to mimic what App Engine does for you.

Start the proxy like this:

$ cloud_sql_proxy -instances=<project-id>:us-west2:<instance-name> -dir /cloudsql

Note if /cloudsql doesn't exist, you'll have to manually create it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1