gpt4 book ai didi

postgresql - 如何在 Docker 容器之间建立连接

转载 作者:IT王子 更新时间:2023-10-29 02:26:59 36 4
gpt4 key购买 nike

当我尝试将我的 goLang GORM 服务连接到 Docker Postgress 容器时遇到连接问题。我认为问题出在连接字符串底部的 golang 代码上。

docker-compose up
Recreating postgress_postgre_1 ... done
Attaching to postgres
postgres | 2018-12-11 21:08:48.283 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres | 2018-12-11 21:08:48.283 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres | 2018-12-11 21:08:48.291 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres | 2018-12-11 21:08:48.316 UTC [20] LOG: database system was shut down at 2018-12-11 21:08:44 UTC
postgres | 2018-12-11 21:08:48.328 UTC [1] LOG: database system is ready to accept connections

===当我运行 golang 时,我得到... panic :无法连接数据库

===============docker-compose.yml

version: '3.6'
services:
postgre:
image: postgres:11.1-alpine
ports:
- '5432:5432'
network_mode: bridge
container_name: postgres

environment:
POSTGRES_USER: 'user'
POSTGRES_PASSWORD: 'password'
POSTGRESS_DB: 'db_amex01'
volumes:
- ./init:/docker-entrypoint-initdb.d/

==== main.go

主要包

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

"github.com/gorilla/mux"
"github.com/jinzhu/gorm"

// _ "github.com/jinzhu/gorm/dialects/sqlite"
_ "github.com/jinzhu/gorm/dialects/postgres"
)

// _ "github.com/jinzhu/gorm/blob/master/dialects/postgres"

type ToDo struct {
gorm.Model
ID int `json:"id"`
TASK_STRING string `json:"task_string"`
DONE bool `json:"done"`
}

var db *gorm.DB
var err error

func main() {
const (
host = "localhost"
port = 5432
user = "postgres"
password = "password"
dbname = "db_amex01"
)


// this is the problem I believe I am having...

db, err := gorm.Open("postgres", "host='postgres' port=5432 user=user dbname='db_amex01' password='password'")



defer db.Close()

if err != nil {
panic("failed to connect database")
}

defer db.Close()

最佳答案

您的撰写文件中有错别字,您将服务命名为 postgre 但连接到 postgres。 Docker 在共享网络上使用服务名称作为 DNS 别名,因此这会中断您的连接尝试。要修复,只需重命名您的服务:

version: '3.6'
services:
postgres:
image: postgres:11.1-alpine
ports:
- '5432:5432'
environment:
POSTGRES_USER: 'user'
POSTGRES_PASSWORD: 'password'
POSTGRESS_DB: 'db_amex01'
volumes:
- ./init:/docker-entrypoint-initdb.d/

关于postgresql - 如何在 Docker 容器之间建立连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53732507/

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