0

I have created a database in GCP but when I try to connect it with my Node.js server on localhost I'm getting the following error:

    original: Error: connect ETIMEDOUT 35.202.153.108:5432
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
    errno: -4039,
    code: 'ETIMEDOUT',
    syscall: 'connect',
    address: '35.202.153.108',
    port: 5432
  }

Here is my code in db.js:

const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(
  process.env.DATABASE_NAME,
  process.env.DATABASE_USERNAME,
  process.env.DATABASE_PASSWORD,
  {
    host: process.env.DATABASE_HOST,//35.202.153.108
    dialect: 'postgres',
  }
);

module.exports = sequelize;


db.authenticate()
  .then((t) => console.log('Connection has been established successfully.'))
  .catch((error) => console.error('Unable to connect to the database:', error));

Can someone help me with connecting to GCP database?

2 Answers 2

1

Try this one:

Create a TCP connection by using Node.js

const createTcpPool = config => {
  // Extract host and port from socket address
  const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432'

  // Establish a connection to the database
  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: dbSocketAddr[0], // e.g. '127.0.0.1'
      port: dbSocketAddr[1], // e.g. '5432'
    },
    // ... Specify additional properties here.
    ...config,
  });
};

The link as well content several other examples for TCP, Socket, SQL and even how to retry connections to Cloud SQL for Postgres in Google Cloud using node.js, php and some others.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use Cloud SQL Proxy to connect to your Cloud SQL from localhost. Then your app connects with the Cloud SQL Proxy with host name=localhost.

Basically, after setting up Cloud SQl Proxy, your app acts like the database is hosted locally but it is actually talking with the Proxy and Proxy is talking with your Cloud SQL instance.

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.