PHP app engine cannot connect to cloud sql

5,807 views
Skip to first unread message

Kevin Lau

unread,
Sep 29, 2016, 6:11:22 PM9/29/16
to Google App Engine

I am trying to connect my app engine PHP app to cloud sql via unix socket (I assume that is correct so that I don't have to connect to the ip). The connect via IP works but the unix socket does not. Any ideas? It's also weird that when I ssh into the box, I don't see any /cloudsql/ directory. I can create it by manually starting cloud_sql_proxy but that doesn't persist as soon as I turn debug off.


I'm using: $db = new pdo( 'mysql:unix_socket=/cloudsql/testproject-xxxxxx:us-central1:library;dbname=books', 'phpapp', // username 'somepw' // password );

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

Kevin Lau

unread,
Sep 29, 2016, 6:36:04 PM9/29/16
to Google App Engine
Figured this out, it was adding this to the app.yaml

beta_settings:
      cloud_sql_instances
: "<INSTANCE_CONNECTION_NAME>"

Abinav Chandar

unread,
Apr 30, 2017, 11:08:15 PM4/30/17
to Google App Engine
Can this only be done with the PDO or can it also be done with mysql_connect()

Nicholas (Google Cloud Support)

unread,
May 8, 2017, 12:31:45 PM5/8/17
to Google App Engine
Connecting to a Cloud SQL instance requires the use of a Unix socket and the appropriate extension available to the runtime.  mysql and mysqli are enabled by default in the PHP runtime for App Engine.  An example of connecting using mysqli_connect can be found here.  The key element here is the use of the socket argument in the mysqli_connect() call.

Note that the PHP team recommends using PDO or mysqli, not the original mysql.  Are you facing any particular challenges with using mysqli or PDO?

Karthik Sekar

unread,
May 20, 2017, 8:34:45 PM5/20/17
to Google App Engine
Hi Nicolas, 

I still have this same issue I am getting the error SQLSTATE[HY000] [2002] No such file or directory when trying to connect to Cloud SQL from my app engine.
It works fine on my "default" service which is a PHP standard environment.

I have this issue in my custom runtime flexible environment app engine. My custom runtime is based on goole app engine php image gcr.io/google_appengine/php:2017-05-11-11-57
I am using 2nd gen cloud sql with PDO to connect to the instance.Custom runtime is on a different service but under same project as cloud sql.

If i use the unix socket I am getting the error  SQLSTATE[HY000] [2002] No such file or directory
So I tried to use the cloud sql ip as host. In that situation i was getting a connection timeout error.

I also added the beta settings to my app.yaml and used env variables from app.yaml still no luck.
My app.yaml looks like below. My service is basically a pub/sub worker service i want to run a php script.

runtime: custom
env: flexservice: workerentrypoint: php index.phpbeta_settings: cloud_sql_instances: "<project-id>:<zone>:<instance-name>"env_variables: MYSQL_DSN: mysql:unix_socket=/cloudsql/<connect-name>;dbname=<db-name> MYSQL_USER: <username> MYSQL_PASSWORD: <password>

I've been breaking my  head for few days, I am stuck with this, I'd really appreciate some direction from you

Cheers
Karthik

Subash PS

unread,
May 28, 2017, 11:29:56 PM5/28/17
to Google App Engine
I amm also facing the same issue

app.yaml

env: flex
runtime: php
runtime_config:
  document_root: .
env_variables:
  # Replace project, instance, database, user and password with the values obtained
  # when configuring your Cloud SQL instance.
  MYSQL_DSN: mysql:unix_socket=/cloudsqlxxxxxxxxxxxxxxxxxxx;dbname=testdb

  MYSQL_USER: root
  MYSQL_PASSWORD: xxxxxxxxxxxxxx
  MYSQL_DATABASE : testdb
w
beta_settings:
  cloud_sql_instances: "xxxxxxxxxxxxxx"


code sample

$dsn = getenv('MYSQL_DSN');
        $username = getenv('MYSQL_USER');
        $password = getenv('MYSQL_PASSWORD');
        $options = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
        ); 
        try{
            $dbh = new PDO($dsn, $username, $password, $options);
            echo "conneced";exit;
        }catch(Exception $e) {
            print $e->getMessage();exit;
        }

Takashi Matsuo

unread,
Jun 2, 2017, 1:42:20 AM6/2/17
to Google App Engine
Do you guys have sqladmin API enabled?
You can check it at:

--
You received this message because you are subscribed to the Google Groups "Google App Engine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-appengi...@googlegroups.com.
To post to this group, send email to google-a...@googlegroups.com.
Visit this group at https://groups.google.com/group/google-appengine.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-appengine/cd70cbcf-c973-4c32-b54d-06e00aabbf56%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Subash PS

unread,
Jun 2, 2017, 9:07:08 AM6/2/17
to google-a...@googlegroups.com
it is connected from appengine standard environment


Thanks & Regards
Subash.P.S






To unsubscribe from this group and stop receiving emails from it, send an email to google-appengine+unsubscribe@googlegroups.com.
To post to this group, send email to google-appengine@googlegroups.com.

--
You received this message because you are subscribed to a topic in the Google Groups "Google App Engine" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-appengine/IZgep9t3LbI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-appengine+unsubscribe@googlegroups.com.
To post to this group, send email to google-appengine@googlegroups.com.

Karthik Sekar

unread,
Jun 3, 2017, 4:19:34 AM6/3/17
to Google App Engine
Yes like Subhash said it's the same situation for me. I had to spin a compute engine because of this.
I discovered that i had to add the compute engine's external ip to cloud sql's allowed networks list.

I have the sql admin access scope for the compute engine but still I couldn't use unix socket or directly sql host ip
without adding the gce external ip to cloudsql. I think won't be able to use auto scaling because of this?

In the same way  for flexible environment  If I have to add VM instances' ip do cloudsql then again iam 
losing the ability of autoscaling and all the other app engine features.

I am currently running my work on gce, I really like to run it on gae flex custom runtime.
It's for production environment

Can someone from the support team help me with this, please?




Thanks & Regards
Subash.P.S






To unsubscribe from this group and stop receiving emails from it, send an email to google-appengi...@googlegroups.com.
To post to this group, send email to google-a...@googlegroups.com.

--
You received this message because you are subscribed to a topic in the Google Groups "Google App Engine" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-appengine/IZgep9t3LbI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-appengi...@googlegroups.com.
To post to this group, send email to google-a...@googlegroups.com.

SPED MAKER

unread,
Jun 7, 2017, 4:05:23 PM6/7/17
to Google App Engine
i did have the same problem..
You no need use a global variable available in app.yaml.

the sample suggest to use:
 'mysql:unix_socket=/cloudsql/testproject-xxxxxx:us-central1:library;dbname=books',
 but like you said, this method works to PDO....

to connect with mysql_connect you can use:
$server = ":/cloudsql/INSTANCE_CONNECTION_NAME";
$user = 'root'
$pass = "pass";

mysql_connect ($server,$user,$pass);

not forget to use :/cloudsql/...

if to function to you, talk here please.

Thomas Valadez

unread,
Jun 23, 2017, 9:17:13 AM6/23/17
to Google App Engine
is it possible to use mysqli?

SPED MAKER

unread,
Jun 23, 2017, 9:26:59 AM6/23/17
to google-a...@googlegroups.com
Não cheguei a testar com mysqli, mas como a string de conexão é muito parecida.. acho que funciona também....

Pelo que entendi o macete está em: $server = ":/cloudsql/INSTANCE_CONNECTION_NAME";

porque a conexão não fica disponível através de um endereço IP.


Victor Alves
Fones:  4237-7740
Celular: 9.6774-9595

A dúvida é o princípio do conhecimento.


AVISO LEGAL: "As informações existentes nesta mensagem e nos arquivos anexados são para uso restrito. A utilização, divulgação, cópia ou distribuição dessa mensagem por qualquer pessoa diferente do destinatário é proibida. Se essa mensagem foi recebida por engano, favor excluí-la e informar ao remetente pelo endereço eletrônico acima."


--
You received this message because you are subscribed to a topic in the Google Groups "Google App Engine" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-appengine/IZgep9t3LbI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-appengine+unsubscribe@googlegroups.com.
To post to this group, send email to google-appengine@googlegroups.com.

Paulo Henrique

unread,
Jul 4, 2017, 9:02:28 AM7/4/17
to Google App Engine
Hi there! 
I tried your solution but I'm still getting this same error.
Anyone found a way to overcome this... please share with this group. Thanks... 

Paulo Henrique

unread,
Jul 4, 2017, 9:02:29 AM7/4/17
to Google App Engine
Just got it to work now: 
I was not using environment variables as shown in the tutorials. I changed the code to follow their guidelines, but still, could not get it to connect to Cloud SQL.
Turned out that the problem was ridiculously simple. In app.yaml, the env_variables were missing the quotes...

Looks like PHP was parsing the DSN as a folder or file, because of the '\'

So this:


env: flex
runtime: php
runtime_config:
document_root: .
env_variables:
# Replace USER, PASSWORD, DATABASE, and CONNECTION_NAME with the
# values obtained when configuring your Cloud SQL instance.
MYSQL_USER: user
MYSQL_PASSWORD: password
MYSQL_DSN: mysql:dbname=db_scope;unix_socket=/cloudsql/xxxx
# Use the connection name obtained when configuring your Cloud SQL instance.
beta_settings:
cloud_sql_instances: xxxxx

Changed to this:

env: flex
runtime: php
runtime_config:
document_root: .
env_variables:
# Replace USER, PASSWORD, DATABASE, and CONNECTION_NAME with the
# values obtained when configuring your Cloud SQL instance.
MYSQL_USER: 'user'
MYSQL_PASSWORD: 'password'
MYSQL_DSN: 'mysql:dbname=DBNAME;unix_socket=/cloudsql/xxxxxx'
# Use the connection name obtained when configuring your Cloud SQL instance.
beta_settings:
cloud_sql_instances: 'xxxxxxx'

SPED MAKER

unread,
Jul 4, 2017, 9:19:10 AM7/4/17
to google-a...@googlegroups.com
Share you code.

--
You received this message because you are subscribed to a topic in the Google Groups "Google App Engine" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-appengine/IZgep9t3LbI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-appengine+unsubscribe@googlegroups.com.
To post to this group, send email to google-appengine@googlegroups.com.
Visit this group at https://groups.google.com/group/google-appengine.

Paulo Henrique

unread,
Jul 4, 2017, 12:22:19 PM7/4/17
to google-a...@googlegroups.com

The problem was inside app.yaml as exposed above. Just just ensure to wrap your connection variables between quotes, so PHP doesn't parse the DSN as local path.


Em ter, 4 de jul de 2017 10:19, SPED MAKER <sped....@gmail.com> escreveu:
Share you code.

Em 4 de jul de 2017 10:02 AM, "Paulo Henrique" <insol...@gmail.com> escreveu:
Hi there! 
I tried your solution but I'm still getting this same error.
Anyone found a way to overcome this... please share with this group. Thanks... 

--
You received this message because you are subscribed to a topic in the Google Groups "Google App Engine" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-appengine/IZgep9t3LbI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-appengi...@googlegroups.com.
To post to this group, send email to google-a...@googlegroups.com.

--
You received this message because you are subscribed to a topic in the Google Groups "Google App Engine" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-appengine/IZgep9t3LbI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-appengi...@googlegroups.com.
To post to this group, send email to google-a...@googlegroups.com.

Abdulaziz Yaakup

unread,
Oct 11, 2017, 9:08:14 AM10/11/17
to Google App Engine
Hi, I also faced same issue on this GAE flex env. But, I solve it by adding the GAE instance VM's ip address to the Cloud SQL Authorized Network. Btw, if I set using unix_socket connection at MYSQL_DSN did not work at all for me. So, just set it with host and database name ("mysql:host=<HOST>;dbname=<DB NAME>;port=<PORT>"), only work for me.

Thanks

Lendi App

unread,
Oct 28, 2017, 4:35:48 PM10/28/17
to Google App Engine
Hi,

I am receiving  mysqli_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: Name or service not known
I have the following 
$socket_prod=":/cloudsql/projectid:europe-west1:databaseinstance";
$dbuser_prod="root";
$dbpass_prod="root_pasw";
$dbname_prod="db_name";

$conn = mysqli_connect($socket_prod,$dbuser_prod,$dbpass_prod,$dbname_prod);

I have  an Google Engine App running  a php service trying to connect to a Google SQL instance in the same project.

Any help?

Attila-Mihaly Balazs

unread,
Oct 31, 2017, 3:16:23 PM10/31/17
to Google App Engine
I'm no PHP expert, but I believe that for mysqli_connect to work with Unix Domain Sockets, one must specify "localhost" for the host and the socket as the last parameter. From here: https://stackoverflow.com/a/13771199/1265

The syntax would be: mysqli_connect("localhost", $dbuser_prod,$dbpass_prod,$dbname_prod, $socket_prod);

Also, take care that you're $socket_prod contains an extra ":" at the start.

Regards,
Attila

Ravi Shanker

unread,
Apr 12, 2018, 9:34:56 AM4/12/18
to Google App Engine
I am also facing same issue in laravel with APP engine , Yes I have enabled API 

SPED MAKER

unread,
Jun 19, 2018, 11:09:21 AM6/19/18
to google-a...@googlegroups.com
Sorry to bring subject to again.
Before i was using mysql_query but because the change the php version i migrate to query.

I read in de somewhere that GAE not work with mysqli, you managed to make it work 



Victor Alves
Fones:  3892-7580
Celular: 9.4711-7418

A dúvida é o princípio do conhecimento.


AVISO LEGAL: "As informações existentes nesta mensagem e nos arquivos anexados são para uso restrito. A utilização, divulgação, cópia ou distribuição dessa mensagem por qualquer pessoa diferente do destinatário é proibida. Se essa mensagem foi recebida por engano, favor excluí-la e informar ao remetente pelo endereço eletrônico acima."

--
You received this message because you are subscribed to a topic in the Google Groups "Google App Engine" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/google-appengine/IZgep9t3LbI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to google-appengine+unsubscribe@googlegroups.com.
To post to this group, send email to google-appengine@googlegroups.com.

Jukka Hautakorpi

unread,
May 31, 2020, 3:11:05 PM5/31/20
to Google App Engine
With php 5.6 application sql-connection was working fine with mysqli procedural.
But not with FLEX

Turns out that you need:

php.ini with
mysqli.default_socket="/cloudsql/xxxxxprojectname:europe-west1:yyysqlinstancename"

And in app.yaml, maybe not both..
env_variables:
  CLOUDSQL_CONNECTION_NAME: "xxxxxprojectname:europe-west1:yyysqlinstancename"

beta_settings:
  cloud_sql_instances: "xxxxxprojectname:europe-west1:yyysqlinstancename"

And also when connecting, cannot leave server address empty anymore, but put localhost
    $db_host  =  'localhost';
    $db_user  =  "root"; // mySQL database user
    $db_password  =  "zzzz"; // mySQL database password
    $db_name  =  "nnnnnn"; // the name of your mySQL database
    $db_socket  =  "/cloudsql/xxxxxprojectname:europe-west1:yyysqlinstancename"; //no : in starting of this string!
    $db_port = null;
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_name, $db_port, $db_socket);


Reply all
Reply to author
Forward
0 new messages