管理员和迁移无法连接到 Postgresql Docker 容器
Adminer & Migrate Can't Connect to Postgresql Docker Container
我有三个 docker 容器(postgresql、adminer 和 go/migrate)并且我已经向主机公开了 adminer 和 postgres 端口。我可以在我的浏览器中访问adminer,postico也可以连接到DB。当我尝试从管理员内部连接到数据库时,它会抛出此错误:
SQLSTATE[08006] [7] could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP
connections on port 5432? could not connect to server: Address not available
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?
迁移容器也抛出这个错误:
error: dial tcp: 127.0.0.1:5432: connect: connection refused
因此,显然容器之间的通信方式存在问题。我需要创建一个 docker 网络吗?
version: '3.1'
services:
db:
image: postgres
environment:
POSTGRES_DB: mydbname
POSTGRES_USER: mydbuser
POSTGRES_PASSWORD: mydbpwd
ports:
- "5432:5432"
migrate:
image: migrate/migrate
volumes:
- .:/migrations
command: ["-database", "postgres://mydbuser:mydbpwd@localhost:5432/mydbname?sslmode=disable", "-path", "/migrations", "up"]
links:
- db
adminer:
image: adminer
restart: always
ports:
- "8081:8080"
depends_on:
- db
您不需要创建链接,docker-compose 创建默认网络。服务到服务的通信也应使用服务名称,localhost
表示此容器(迁移)而不是 DB
容器。
将localhost
更改为db
migrate:
image: migrate/migrate
volumes:
- .:/migrations
command: ["-database", "postgres://mydbuser:mybpwd@db:5432/mydbname?sslmode=disable", "-path", "/migrations", "up"]
因为您 DB
服务名称是 db
所以您使用它的名称连接 db
容器。
我有三个 docker 容器(postgresql、adminer 和 go/migrate)并且我已经向主机公开了 adminer 和 postgres 端口。我可以在我的浏览器中访问adminer,postico也可以连接到DB。当我尝试从管理员内部连接到数据库时,它会抛出此错误:
SQLSTATE[08006] [7] could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP
connections on port 5432? could not connect to server: Address not available
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?
迁移容器也抛出这个错误:
error: dial tcp: 127.0.0.1:5432: connect: connection refused
因此,显然容器之间的通信方式存在问题。我需要创建一个 docker 网络吗?
version: '3.1'
services:
db:
image: postgres
environment:
POSTGRES_DB: mydbname
POSTGRES_USER: mydbuser
POSTGRES_PASSWORD: mydbpwd
ports:
- "5432:5432"
migrate:
image: migrate/migrate
volumes:
- .:/migrations
command: ["-database", "postgres://mydbuser:mydbpwd@localhost:5432/mydbname?sslmode=disable", "-path", "/migrations", "up"]
links:
- db
adminer:
image: adminer
restart: always
ports:
- "8081:8080"
depends_on:
- db
您不需要创建链接,docker-compose 创建默认网络。服务到服务的通信也应使用服务名称,localhost
表示此容器(迁移)而不是 DB
容器。
将localhost
更改为db
migrate:
image: migrate/migrate
volumes:
- .:/migrations
command: ["-database", "postgres://mydbuser:mybpwd@db:5432/mydbname?sslmode=disable", "-path", "/migrations", "up"]
因为您 DB
服务名称是 db
所以您使用它的名称连接 db
容器。