简体   繁体   中英

cannot connect nodejs app engine to postgres cloud sql

I recently began using google cloud and I wanted to host my Postgres database to google cloud and deployed my node js application to app engine however I am having issues connecting my nodejs app to the hosted database, I have already enabled the Cloud SQL API. I use node-postgres here is my connection object:

const { Pool } = require("pg");
const pool = new Pool({
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  port: 5432,
  host: `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`,
  database: process.env.DB_NAME,
});

module.exports = pool;

This is the query:

router.get("/", async (req, res) => {
  try {
    const { rows } = db.query("SELECT * FROM users ORDER BY id DESC");
    res.json(rows);
  } catch (err) {
    console.error(err);
  }
});

this is my app.yaml:

runtime: nodejs14

env_variables:
  DB_USER: postgres
  DB_PASS: password here
  DB_NAME: the db name here
  CLOUD_SQL_CONNECTION_NAME: my connection name here

beta_settings:
  cloud_sql_instances: my connection name here

when I run this I get an ENONET error:

UnhandledPromiseRejectionWarning: Error: connect ENOENT /cloudsql/instance_id/.s.PGSQL.5432
    at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:121478) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:121478) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I am not sure what exactly happened, I followed the official documentation but it still didnt succeed.

I think that your problem is that in your connection object, the field "host" expects an IP address and it looks like you're putting in the UNIX socket name mentioned in some pages of the documentation. Try to put in the valid public or private IP address of your Cloud SQL instance instead as that's what the library you're using expects in this case.

Also, make sure that you configure your App Engine correctly in each case(public or private IP) like in this documentation page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM