Right way to connect to Google Cloud SQL from Node.JS

VS_FF picture VS_FF · Feb 28, 2017 · Viewed 9.2k times · Source

I followed the example on how to set up Node.JS to work with Cloud SQL, and generally got it to work, but with some workarounds on how to connect to the SQL server. I am unable to connect in the proper way passing the INSTANCE_CONNECTION_NAME to the socketPath option of the options variable for the createConnection() method. Instead, as a temporary workaround, I currently specify the server's IP address and put my VM IP address into the server's firewall settings to let it through.

This all works, but I'm now trying put it together properly before publishing to AppEngine.

How can I get it to work?

The following code works fine:

function getConnection ()
{
  const options = 
  {  
    host: "111.11.11.11", //IP address of my Cloud SQL Server
    user: 'root',
    password: 'somePassword',
    database: 'DatabaseName'
  };
  return mysql.createConnection(options);
}

But the following code, which I am combining from the Tutorial and from the Github page, which is referred to in the Tutorial, is giving errors:

function getConnection ()
{
  const options = 
  {  
    user: 'root',
    password: 'somePassword',
    database: 'DatabaseName',
    socketPath: '/cloudsql/project-name-123456:europe-west1:sql-instance-name'
  };
  return mysql.createConnection(options);
}

Here's the error that I'm getting:

{ [Error: connect ENOENT /cloudsql/project-name-123456:europe-west1:sql-instance-name]
  code: 'ENOENT',
  errno: 'ENOENT',
  syscall: 'connect',
  address: 'cloudsql/project-name-123456:europe-west1:sql-instance-name',
  fatal: true }

What am I doing wrong? I am concerned that if I publish the app to AppEngine with the IP address, I won't be able to allow the incoming traffic into the SQL server?

Answer

Kwan-ki Ahn picture Kwan-ki Ahn · Aug 8, 2017

I met similar error while testing 'coud sql'.

  • error message : Error: connect ENOENT /cloudsql/xxx-proj:us-central1:xxx-instance
  • solution :

+----------------------------------------------------------+
wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
chmod +x cloud_sql_proxy
sudo mkdir /cloudsql; sudo chmod 777 /cloudsql
./cloud_sql_proxy -dir=/cloudsql &

=> now node js server can connect to mysql

refer to guide : https://cloud.google.com/appengine/docs/flexible/nodejs/using-cloud-sql