将 Google App Engine 连接到 GCE 上的 PostgreSQL 数据库

Connect Google App Engine to PostgreSQL database on GCE

我是 Google Cloud 的新手。我已经在 Google Compute Engine [as per this tutorial] and I have deployed Node.js on Google App Engine [following this guide].

上设置了 PostgreSQL

我的app.js代码如下:

const express = require('express');
const pg = require('pg');
const app = express();

const PORT = process.env.PORT || 8080;

var config = 'postgresql://username:password@[VM Instance External IP]:5432/database'
var client = new pg.Client(config);

client.connect();

app.enable('trust proxy');

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.sendFile('/index.html', {root: __dirname })
});

app.get('/look', (req, res) => {
    client.query(
        'SELECT * FROM users', function(err, result, fields){
            if (err) throw err;
            res.send(result);
        }
    );
});

app.listen(PORT,() => {
  console.log(`Server is listening on port ${PORT}`);
});

我设置了以下防火墙规则:

NAME       NETWORK  DIRECTION  PRIORITY  ALLOW      IP RANGES   DENY  DISABLED
postgres   default  INGRESS    1000      tcp:5432   0.0.0.0/0         False

我已编辑 postgresql.conf 以使 Postgres 能够侦听所有 IP 地址:

listen_addresses = '*'

并在 pg_hba.conf 文件中添加了以下行:

host    all             all           0.0.0.0/0          md5

当我 运行 它在我的机器上时,它成功连接到 Postgres。但是,当我在 Google App Engine 上 运行 它时,我得到以下响应代码(意味着连接在通过服务器处理请求的过程中关闭):

499

非常感谢您的帮助。非常感谢!

您是否考虑过为您的数据库使用 Google Cloud SQL?拥有托管数据库,而不是虚拟机中的 运行 数据库,长期维护起来会更容易一些,并且会以安全的方式简化连接服务。甚至还有关于设置它的教程!

https://cloud.google.com/sql/docs/mysql/connect-app-engine-standard

A​​pp Engine 永远不会以这种方式连接到您的 VM 实例,实际上这个问题在 SO 中很常见(例如,this question)。

要连接到您的 VM,您应该创建一个 VPC Serverless Connector which will allow you to access resources inside the VPC like in your case a VM or any others like Memorystore. You can follow these steps 然后,在您的代码中而不是使用 VM 的 public IP,您可能想要使用虚拟机,即:

var config = 'postgresql://username:password@[VM Instance Internal IP]:5432/database'

如果其他配置没有问题(防火墙、服务 运行 等),您将能够连接到您的数据库。