1

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();

1 Answer 1

1

/solved

Alas as soon as you ask for help you discover the issue.

If you're using Cloud SQL Proxy locally the hostname is localhost/127.0.0.1, in Cloud run the hostname is /cloudsql/INSTANCE_CONNECTION_NAME:

Once correctly configured, you can connect your service to your Cloud SQL instance's Unix domain socket accessed on the environment's filesystem at the following path: /cloudsql/INSTANCE_CONNECTION_NAME.

The INSTANCE_CONNECTION_NAME uses the format project:region:instance-id. You can find it on the Overview page for your instance in the Google Cloud console or by running the following command:

gcloud sql instances describe [INSTANCE_NAME]

These connections are automatically encrypted without any additional configuration.

The code samples shown below are extracts from more complete examples on the GitHub site. Click View on GitHub to see more.

Note: The PostgreSQL standard requires a .s.PGSQL.5432 suffix in the socket path. Some libraries apply this suffix automatically, but others require you to specify the socket path as follows:

/cloudsql/INSTANCE_CONNECTION_NAME/.s.PGSQL.5432
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.