Google Cloud Functions - Connect to Cloud SQL via SSL
Asked Answered
T

1

1

The GCF Cloud SQL documentation does not show how to connect via the socket using SSL. Here is my config, however when I try to connect I get an ECONNREFUSED error. But when I try to connect to a non-SSL database it works fine. Any ideas?

const mysql = require('mysql');

const mysqlConfig = {
  connectionLimit: 1,
  user: dbUser,
  password: dbPassword,
  database: dbName,
  ssl: {
    ca: await getFileContents(bucketName, ssl.ca_filename),
    key: await getFileContents(bucketName, ssl.key_filename),
    cert: await getFileContents(bucketName, ssl.cert_filename)
  }
};
if (process.env.NODE_ENV === 'production') {
  mysqlConfig.socketPath = `/cloudsql/${connectionName}`;
}

// Connection pools reuse connections between invocations,
// and handle dropped or expired connections automatically.
let mysqlPool;

exports.mysqlDemo = (req, res) => {
  // Initialize the pool lazily, in case SQL access isn't needed for this
  // GCF instance. Doing so minimizes the number of active SQL connections,
  // which helps keep your GCF instances under SQL connection limits.
  if (!mysqlPool) {
    mysqlPool = mysql.createPool(mysqlConfig);
  }

  mysqlPool.query('SELECT NOW() AS now', (err, results) => {
    if (err) {
      console.error(err);
      res.status(500).send(err);
    } else {
      res.send(JSON.stringify(results));
    }
  });
};
Tufthunter answered 19/6, 2019 at 9:0 Comment(0)
H
1

Connections between Cloud Functions and Cloud SQL work in the same way as connections from App Engine . As such SSL/TLS connections are needed only when you are connecting to Cloud SQL using public IP addresses. If Cloud SQL Proxy or the Java Socket Library, is used, setting up SSL is not required encryption happen by default.

How to set this up is set in the following document: https://cloud.google.com/functions/docs/sql#connecting_to_cloud_sq

For an explanation as to how the connections are implemented please have a look at: https://cloud.google.com/sql/docs/mysql/configure-ssl-instance

Horntail answered 19/6, 2019 at 10:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.