include beta_settings
to app.yaml
to enable cloud proxy on the instance in production, and specify the UNIX socket socketPath
in config
, so your flex app can connect to the instance via proxy.
socketPath
should be in config
only if the app is running in production on App Engine. For local development, the TCP socket is used with the proxy client, that you need to install and start with the following commands:
wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
chmod +x cloud_sql_proxy
./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:3306
here's an example of Node app that connects and queries a Cloud MySQL instance using the proxy. The if
statement permits the app to switch configuration dev-local/prod-appengine automatically, using environment variables .
app.yaml
runtime: nodejs
env: flex
env_variables:
SQL_USER: [SQL_USER]
SQL_PASSWORD: [SQL_PASSWORD]
SQL_DATABASE: [DATABASE_NAME]
INSTANCE_CONNECTION_NAME: [INSTANCE_CONNECTION_NAME]
beta_settings:
cloud_sql_instances: [INSTANCE_CONNECTION_NAME]
package.json
{
"engines": {
"node": "8.x.x"
},
"dependencies": {
"express": "4.16.3",
"mysql": "^2.15.0"
},
"scripts": {
"start": "node server.js"
}
}
server.js
const express = require('express');
const mysql = require('mysql');
const app = express();
var config = {
user: process.env.SQL_USER,
database: process.env.SQL_DATABASE,
password: process.env.SQL_PASSWORD
}
if (process.env.INSTANCE_CONNECTION_NAME && process.env.NODE_ENV === 'production') {
config.socketPath = `/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}`;
}
var connection = mysql.createConnection(config);
connection.connect();
app.get('/', (req, res) => {
connection.query(
'SELECT * FROM entries', function(err, result, fields){
if (err) throw err;
res.send(result);
}
);
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});