Ahmed Abdallah
Ahmed Abdallah

Reputation: 51

Sequelize can't access GCP Cloud SQL

I have a Google cloud SQL instance and I want to be able to access it from my node.js application running locally on my machine.

I have enabled Cloud SQL instance access through public IP and created a network on GCP with my local machine IP and I have tested the connection in several ways:

  1. MySQL Workbench
  2. terminal
  3. From my NodeJS application running locally using mysql2 to connect

All the above mentioned ways connected successfully and I can work on my cloud SQL instance as expected, the problem is when trying to allow my NodeJS app to connect using sequelize, I can see this error

UnhandledPromiseRejectionWarning: SequelizeAccessDeniedError: Access denied for user 'root'@'localhost' (using password: YES)

this is my connection code:

    host: 'XXX.XX.XX.XX',
    port: "",
    user: "root",
    password: 'password',
    database: "DB_NAME",
    dialect: "mysql",
    pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
   
    const db = {};              
    const connection = await mysql.createConnection({ host, port, user, password });
    await connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
    const sequelize = new Sequelize(database, user, password, { dialect: dialect });
    
    db.Sequelize = Sequelize;
    db.sequelize = sequelize;
    
    // // init models and add them to the exported db object
    db.orders = require("../../models/order.model.js")(sequelize, Sequelize);
         
    db.sequelize.sync().then(function(){
              console.log('DB connection sucessful.');
            }, function(err){
              // catch error here
            
            });

Upvotes: 0

Views: 732

Answers (1)

Ahmed Abdallah
Ahmed Abdallah

Reputation: 51

It Seems that I should pass the host as somehow it was considering host to be localhost when it is not explicitly specified

So this:

    const sequelize = new Sequelize(database, user, password, { dialect: dialect });

Should be updated to this:

    const sequelize = new Sequelize(database, user, password, { host: host, dialect: dialect });

Upvotes: 1

Related Questions