gcloud sql连接无法正常工作

I have uploaded a CodeIgniter project on google cloud APP engine with Flexible Environment

Getting bellow error, while connecting the SQL Instance

SQLSTATE[HY000] [2002] No such file or directory

Filename: core/CodeIgniter.php

Line Number: 518

application/config/database.php

$db['default'] = array(
    'dsn'   => 'mysql:unix_socket=/cloudsql/<instance-connection-name>;dbname=<data-base-name>',
    'hostname' => 'localhost',
    'username' => USERNAME,
    'password' => PASSWORD,
    'database' => DATABASE,
    'dbdriver' => 'pdo',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

app.yaml

runtime: php
env: flex

runtime_config:
    document_root: .

env_variables:
    MYSQL_USER: USER
    MYSQL_PASSWORD: PASSWORD
    MYSQL_DSN: mysql:dbname=<database>;unix_socket=/cloudsql/<instance-connection-name>

beta_settings:
    cloud_sql_instances: <instance-connection-name>

Have experienced the same case with a Symfony 4 project. My findings on that:

When I first deployed the app on the App engine and the hostname was set:

'hostname' => 'localhost'

I got this error:

SQLSTATE[HY000] [2002] No such file or directory

Afterwords I just removed the above line ('hostname' => 'localhost') and deployed the app again. This worked for me

On the next deployments I added again the hostname with localhost and it worked.

Conclusion

  • First time deploy: remove/delete the hostname paremeter
  • After first deploy you can use set the hostname ('hostname' => 'localhost') again