How to integrate Heroku with Google Cloud SQL (native - GCP) in Nestjs/Typeorm?

Viewed 278

I'm currently really frustating cause cannot deploy my app to Heroku and connect my db to Google Cloud SQL.

What am I already did?

  • I have been set up SSL to connect them
  • I have been set up Cloud SQL Auth Proxy (+ set up Cloud SQL CLient role in IAM Manager)
  • I have been did buildpacks via Heroku approaches etc.

And overall failed.

This is my config database via Typeorm in Nestjs.

    import { TypeOrmModuleOptions } from "@nestjs/typeorm"
    const fs = require("fs");
    require('dotenv').config()

    export class OrmConfig {
        // Config TypeOrm
        getConfig() {
             const ormConfig: TypeOrmModuleOptions = {
                 type: 'postgres',
                 url: 'postgres://myusername:mypassword@myhostincloudsql(publicip):5432/mydb',
                 // host: 'myhostincloudsql(public ip)',
                 // port: 5432,
                 // username: 'myusername',
                 // password: 'mypassword',
                 // database: 'mydb',
                 entities: ['dist/**/*.entity{.js,.ts}'],
                 synchronize: false,
                 migrationsRun: true,
                 logging: false,
                 logger: 'file',
                 migrations: [
                     'dist/database/migrations/**/*{.js, .ts}'
                 ],
                 cli: {
                     migrationsDir: 'database/migrations'
                 },
                 ssl: true,
                 extra: {
                      ssl: {
                           ca: fs.readFileSync('./src/config/server-ca.pem'),
                           cert: fs.readFileSync('./src/config/client-cert.pem'),
                           key: fs.readFileSync('./src/config/client-key.pem'),
                           // rejectUnauthorized: false
                      }
                 }
            }

            return ormConfig
        }
    }

    export default new OrmConfig().getConfig()

This is my app.module.ts

    import { SendGridModule } from '@anchan828/nest-sendgrid';
    import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
    import { ConfigModule } from '@nestjs/config';
    import { TypeOrmModule } from '@nestjs/typeorm';
    // import { BlogModule } from './blog/blog.module';
    import OrmConfig from './config/ormConfig';
    import { BusinessContactModule } from './contact/business/business.module';
    import { InvestorNotificationController } from './contact/investor/investment-recommendation/investor-notification.controller';
    import { InvestmentRecommendationModule } from './contact/investor/investment-recommendation/investor-notification.module';
    import { InvestorContactModule } from './contact/investor/angel-investor/investor.module';
    import { EmitenCampaignModule } from './emiten-campaign/emiten-campaign.module';
    import { EmitenModule } from './emiten/emiten.module';
    import { FlashMobileModule } from './flash-mobile/flash-mobile.module';
    import { CoreModule } from './global/core.module';
    import { Agent } from './middleware/agent';
    import { AuthModule } from './middleware/auth.module';
    import { TekenajaModule } from './tekenaja/tekenaja.module';
    import { UserModule } from './user/user.module';
    require('dotenv').config();

    @Module({
       imports: [
         /**
         * ================================
         * Typeorm Config
         * ================================
         */
         SendGridModule.forRoot({
           apikey: process.env.SENDGRID_API_KEY,
         }),
         TypeOrmModule.forRoot(OrmConfig), // This is I call it
         ConfigModule.forRoot(),
         AuthModule,
         TekenajaModule,
         FlashMobileModule,
         CoreModule,
         EmitenModule,
         EmitenCampaignModule,
         // InvestorContactModule,
         // BusinessContactModule,
         UserModule,
         // BlogModule
         InvestmentRecommendationModule
       ]
     })
     export class AppModule implements NestModule { 
       configure(consumer: MiddlewareConsumer) {
         consumer
         .apply(Agent)
         .forRoutes('/');
       }
     }

NB: Anyway, I'm using public ip in Google Cloud SQL

I have tried connect it from Heroku Postgres, and works. And I try with Cloud SQL fields, getting error something like this

Error response

Now, what should I do in order to connected between them? I hope reply my issue guys. Many thanks.

3 Answers

Try running the Cloud SQL Proxy in addition to your app in the same dynamo.

For example:

web: trap '' SIGTERM; ./cloud_sql_proxy -credential_file sa.json -instances=INSTANCE_CONN_NAME=tcp:5432 & npm start & wait -n; kill -SIGTERM -$$; wait

Note, you'll need to ensure the Cloud SQL Proxy binary and a credential file is included with your app. And you won't want to check those into source control.

See https://help.heroku.com/CTFS2TJK/how-do-i-run-multiple-processes-on-a-dyno.

In CloudSQL - your instance must have Public IP address ( section Connection ) and you need address IP in Authorised network from where you will try connect. Ofc you can setup 0.0.0.0 but don't do it. Better way is setup ssh connection.

Public Adress

I have solved my issue. As mentioned @Sebastian Pietrzak, I should implemented 0.0.0.0/0 in Authorized Network in the Connection Menu. And for the additional you have to set the SSL appoach.

enter image description here

Many thanks everyones

Related