Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting Sequelize to Google Cloud SQL

does anyone know how to connect to Google Cloud SQL from Sequelize?

  sequelize = new Sequelize(process.env.TEST_DB || 'postgres', 'blah', null, {
    dialect: 'postgres',
    operatorsAliases: Sequelize.Op,
    host: process.env.DB_HOST || 'localhost',
    define: {
      underscored: true
    },
  });
  connected = true;
like image 856
steph Avatar asked Dec 24 '22 04:12

steph


2 Answers

index.js

const sequelize = new Sequelize('{db_name}', '{db_user}', '{db_password}', {
  dialect: 'mysql',
  host: '/cloudsql/{instance}',
  timestamps: false,
  dialectOptions: {
    socketPath: '/cloudsql/{instance}'
},
});

add this in serverless.yml

beta_settings:
  cloud_sql_instances: {xxxxxxx-xxxxxx:us-central1:xxxxxxxxxxx}
like image 75
Marcos Dávalos Avatar answered Dec 28 '22 10:12

Marcos Dávalos


You can connect from Sequelize like from any other client tool or ORM. Getting the access correctly depends on where you are running your code. If you code runs outside GCP, you can follow the external app instructions on this page: https://cloud.google.com/sql/docs/postgres/connect-external-app.

If you are using proxy in your local computer, you set process.env.DB_HOST to 127.0.0.1. You can find troubleshooting tips at https://cloud.google.com/sql/docs/postgres/sql-proxy#troubleshooting.

like image 26
Veikko Avatar answered Dec 28 '22 10:12

Veikko