我有一个关于 docker 的问题
func ConnectToDB() {
var err error
dsn := "host=localhost user=postgres password=postgres dbname=yandex port=5432 sslmode=disable"
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("failed to connect with database")
}
}
这是我连接到数据库的函数
这是我的 docker-compose 文件
version: "3.8"
services:
server:
container_name: server
build:
context: .
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
ports:
- "8080:8080"
volumes:
- type: bind
source: ./static
target: /app/static
environment:
POSTGRES_PASSWORD: "postgres"
postgres:
container_name: storage
image: postgres:16.2
restart: unless-stopped
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
POSTGRES_DB: yandex
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U postgres" ]
interval: 10s
timeout: 5s
retries: 5
ports:
- "5432:5432"
volumes:
- type: bind
source: ./init.sql
target: /docker-entrypoint-initdb.d/init.sql
所以在命令之后 docker-compose 构建 docker-compose up 这给了我一个错误
服务器 | [错误] 未能初始化数据库,出现错误无法连接到
host=localhost user=postgres database=yandex
:拨号错误(拨号 tcp [::1]:5432:连接:无法分配请求的地址)
服务器 | 2024/05/02 20:17:58 连接数据库失败
你能告诉我我做错了什么吗?
我尝试在函数中更改 localhost 像这样
func ConnectToDB() {
var err error
dsn := "host=postgres user=postgres password=postgres dbname=yandex port=5432 sslmode=disable"
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("failed to connect with database")
}
}
这有效了
但是为什么呢?
假设 go 代码在您的
server
容器内运行:
使用“localhost”不起作用,因为在服务器容器内没有数据库在本地主机上运行(它在您的主机上运行,而不是在该容器内)
将“localhost”更改为“postgres”是有效的,因为 docker 正在管理您的
server
容器中的 dns,并使用您在 docker-compose 定义中指定的名称定义到数据库的路由 (postgres
)。
这有道理吗?