首页 > 解决方案 > AWS SAM golang lambda localhost连接拒绝postgres

问题描述

我无法将 AWS SAM lambda 函数连接到本地 postgres 实例。我稍后会具体说明,但首先让我说相同的代码适用于我的同事,并且我尝试在 docker 容器中使用 Postgres 以及手动安装。为了简化问题,我从 SAM helloworld golang 示例重新开始,并添加了以下内容:

import (
  _ "github.com/lib/pq"
  "database/sql"
)
.
.
.
const (
    host     = "localhost"
    port     = 5432
    user     = "postgres"
    password = "postgres"
    dbname   = "postgres"
)
.
.
.
.
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
    "password=%s dbname=%s sslmode=disable",
    host, port, user, password, dbname)

db, err := sql.Open("postgres", psqlInfo)

if err != nil {
    panic(err)
}
defer db.Close()

err = db.Ping()
if err != nil {
    panic(err)
}

fmt.Println("Successfully connected!")

我收到以下错误:

dial tcp 127.0.0.1:5432: connect: connection refused: OpError
[{"path":"github.com/aws/aws-lambda-go@v1.13.3/lambda/function.go","line":35,"label":"(*Function).Invoke.func1"},{"path":"runtime/panic.go","line":969,"label":"gopanic"},{"path":"hello-world/main.go","line":67,"label":"handler"},{"path":"reflect/value.go","line":475,"label":"Value.call"},{"path":"reflect/value.go","line":336,"label":"Value.Call"},{"path":"github.com/aws/aws-lambda-go@v1.13.3/lambda/handler.go","line":124,"label":"NewHandler.func1"},{"path":"github.com/aws/aws-lambda-go@v1.13.3/lambda/handler.go","line":24,"label":"lambdaHandler.Invoke"},{"path":"github.com/aws/aws-lambda-go@v1.13.3/lambda/function.go","line":67,"label":"(*Function).Invoke"},{"path":"reflect/value.go","line":475,"label":"V
alue.call"},{"path":"reflect/value.go","line":336,"label":"Value.Call"},{"path":"net/rpc/server.go","line":377,"label":"(*service).call"},{"path":"runtime/asm_amd64.s","line":1374,"label":"goexit"}]

SAM CLI,版本 1.21.1

我现在已经在两台机器上尝试过这个并且得到了同样的错误。有什么我只是想念的吗?我可以确认数据库正在接收连接正常。我每天都从节点应用程序中点击它。另外,我可以在 SAM 之外构建 golang 代码,它可以正常工作。所以我的 SAM 设置有问题。

标签: postgresqlgoaws-lambdaaws-sam-clisam

解决方案


弄清楚了。在 lambda 中,我需要将 postgres 连接字符串设置为命中host.docker.internal


推荐阅读