【问题标题】:Connect Google App Engine to PostgreSQL database on GCE将 Google App Engine 连接到 GCE 上的 PostgreSQL 数据库
【发布时间】:2020-12-25 04:32:23
【问题描述】:

我是 Google Cloud 的新手。我已经在 Google Compute Engine [as per this tutorial] 上设置了 PostgreSQL,我已经在 Google App Engine [following this guide] 上部署了 Node.js。

我的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

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

【问题讨论】:

    标签: node.js postgresql google-app-engine google-cloud-platform google-compute-engine


    【解决方案1】:

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

    要连接到您的虚拟机,您应该创建一个VPC Serverless Connector,这将允许您访问 VPC 内的资源,例如您的虚拟机或任何其他资源(例如 Memorystore)。您可以关注these steps,然后在您的代码中,而不是使用虚拟机的公共 IP,您可能想要使用虚拟机的私有 IP,即:

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

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

    【讨论】:

      【解决方案2】:

      您是否考虑过将Google Cloud SQL 用于您的数据库?拥有一个托管数据库,而不是在 VM 中运行一个,将更容易长期维护,并将以安全的方式简化连接服务。甚至还有一个设置它的教程!

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-18
        • 2016-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-07
        • 2020-11-22
        • 2019-09-06
        相关资源
        最近更新 更多