I am following this doc:
https://cloud.google.com/sql/docs/postgres/connect-instance-cloud-functions
The docs seem to be a bit off as there is no mention of creating a connector in the cloud function but its required.
I have it working with the helloworld example but when I try to connect to my AlloyDb and fetch users I get this error: Error: connect ECONNREFUSED 127.0.0.1:543
I set my env variables:
INSTANCE_UNIX_SOCKET : /cloudsql/{my-project-id}:us-east4:quickstart-instance
DB_NAME: {db_name}
DB_USER: {db_user}
DB_PASS: {my_pwd}
I set my Runtime service account to my account with AlloyDb_Admin permissions
Here is my function:
-package.json
{
"dependencies": {
"@google-cloud/functions-framework": "^3.0.0",
"knex": "3.1.0",
"pg": "8.11.5"
}
}
-index.js
const Knex = require('knex');
functions.http('getUsers', async (req, res) => {
const createUnixSocketPool = async config => {
return Knex({
client: 'pg',
connection: {
user: process.env.DB_USER, // e.g. 'my-user'
password: process.env.DB_PASS, // e.g. 'my-user-password'
database: process.env.DB_NAME, // e.g. 'my-database'
host: process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance'
},
...config,
});
};
const knex = await createUnixSocketPool()
knex('users').select('*')
.then(rows => {
console.log(rows);
})
.catch(err => {
console.error(err);
});
});
Here is my network:
Here is my Connector Details:
Here is my firewall for default
:
What might I be missing?
Cloud SQL and AlloyDB are two different products.
While similar, they are still different and the code sample you are referencing is meant for Cloud SQL and won’t work as is for AlloyDB. However, a very similar sample will (an easier to understand one in my opinion).
Since AlloyDB uses a Private IP address by default for the database, I would recommend just connecting directly over a TCP connection to your AlloyDB instance’s Private IP address as follows:
You will want to use the env variable INSTANCE_HOST
instead of INSTANCE_UNIX_SOCKET
and have it be the Private IP address of your instance which you can find on the AlloyDB Overview page
const Knex = require('knex');
functions.http('getUsers', async (req, res) => {
const knex = Knex({
client: 'pg',
connection: {
host: process.env.INSTANCE_HOST, // AlloyDB IP (ex. 10.0.0.1)
port: 5432,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
},
});
await knex('users').select('*')
.then(rows => {
console.log(rows);
})
.catch(err => {
console.error(err);
});
});
7