I'm trying to deploy a container on Google Cloud Run that connects to a postgres db. I've followed the steps in this guide using the Cloud SQL connection setting on the container which I understand auto configures Cloud SQL Proxy but I continue to receive the following error
Error connecting to the database: Error: connect ECONNREFUSED 127.0.0.1:5432
I can successfully connect if I run the container locally with Cloud SQL Proxy running on my machine so the code and sql configuration are correct, the issue is specifically connecting from cloud run.
I've added the role Cloud SQL Client to the service account Cloud run uses.
Example code
const { Client } = require('pg');
async function connectAndQueryPostgres() {
const client = new Client({
host: '127.0.0.1',
port: 5432,
database: 'n8n',
user: 'postgres',
password: 'd&%aG@P#H2WFgHHP'
});
try {
await client.connect();
console.log('Connected to PostgreSQL database');
const result = await client.query('SELECT NOW()');
console.log('Test query result:', result.rows[0]);
} catch (error) {
console.error('Error connecting to the database:', error);
} finally {
await client.end();
console.log('Database connection closed');
}
}
connectAndQueryPostgres();