gpt4 book ai didi

postgresql - 连接 : cannot assign requested address

转载 作者:行者123 更新时间:2023-12-04 11:55:36 24 4
gpt4 key购买 nike

我收到来自 Docker 中的 Go 应用程序的以下错误消息:

panic: failed to connect to `host=localhost user=postgres-dev database=dev`: dial error (dial tcp [::1]:5432: connect: cannot assign requested address)

出现在下一个 Dockerfile的环境中和 docker-compose.yml文件:
FROM golang:latest

WORKDIR /WD

COPY go.mod go.sum ./

RUN go mod download

COPY . .
docker-compose.yml文件:
version: '3'
services:
db:
image: postgres:latest
environment:
POSTGRES_DB: dev
POSTGRES_USER: postgres-dev
POSTGRES_PASSWORD: [~secret~]
ports: 5432:5432
app:
build: .
command: ["./wait-for-it.sh", "db:5432", "--", "go", "run", "main.go"]
volumes:
- .:/WD
ports:
- "8000:8000"
depends_on:
- db
links:
- db


这里是 main.go文件:

package main

import (
"context"
"fmt"
"log"
"net/http"

api "github.com/[placeholder]/[placeholder]/api"

db "github.com/[placeholder]/[placeholder]/db"

pgx "github.com/jackc/pgx/v4"
)

func main() {
fmt.Println("Init")
r := api.InitRoutes()

conn, err := pgx.Connect(context.Background(), "postgresql://postgres-dev:[~secret~]@localhost:5432/dev")
if err != nil {
panic(err) // the error appears from this line.
}

dbInstance := &db.DbService{Conn: conn}

dbInstance.Conn.Ping(context.Background())

dbInstance.Migrate("/db/db.sql")

http.ListenAndServe(":8000", r)
}

这可能有帮助吗?

在控制台日志中,我找到了下一行,我认为这与问题有关:

db_1   | 2019-12-07 08:08:59.350 UTC [1] LOG:  starting PostgreSQL 12.1 (Debian 12.1-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1 | 2019-12-07 08:08:59.351 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
# read the next line:
db_1 | 2019-12-07 08:08:59.351 UTC [1] LOG: listening on IPv6 address "::", port 5432

数据库地址是 :: with port 5432而程序尝试连接到 ::1 with port 5432 ,这可能是问题的原因吗?

最佳答案

在附加到 bridge network 的容器内(默认)localhost (127.0.0.1) 是容器本身。所以你的 app容器正在尝试访问其自身(不在主机或 db 容器上)端口 5432 上的数据库。最简单的解决方法是更改​​连接字符串:
postgresql://postgres-dev:[~secret~]@localhost:5432/dev

postgresql://postgres-dev:[~secret~]@db:5432/dev
注意:我认为您的 docker-compose.yml 中有错字- ports: 5432:5432正在设置环境变量而不是映射端口(请注意,如果 appdb 通信实际上不需要,如果它们都在同一个 bridged network 上,默认情况下)。

注意 2:您应该不需要使用 links在这种情况下(这是一个遗留功能)。

关于postgresql - 连接 : cannot assign requested address,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59224272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com