Adminer & Migrate 无法连接到 Postgresql Docker 容器

3

我有三个 Docker 容器(postgresql、adminer 和 go/migrate),已将 adminer 和 postgres 的端口暴露给主机。我可以在浏览器中访问 adminer,并且 postico 也可以连接到数据库。但当我尝试从 adminer 内部连接数据库时,它会抛出以下错误:

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?

迁移容器也会出现这个错误:
错误:拨号tcp:127.0.0.1:5432:连接被拒绝
因此,容器之间的通信存在问题。我需要创建一个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


1
问题在于迁移容器上没有运行postgres服务。localhost始终指的是容器本身而不是docker主机。请将“localhost”替换为“db”。 - leopal
1个回答

7

您无需创建链接,docker-compose创建默认网络。此外,服务与服务之间的通信应使用服务名称,localhost表示此容器(migrate),而不是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容器。


1
谢谢!看起来容器现在可以与其通信了。当我运行 docker-compose up -d 时,迁移容器会抛出此错误:error: dial tcp 172.22.0.2:5432: connect: connection refused。当我再次运行 docker-compose up migrate 时,它似乎已经解决了连接错误,但现在显示 error: first: file does not exist。我映射卷的方式有问题吗?为了澄清,迁移文件夹位于项目根目录 ./migrations/ 中,似乎 migrate 容器无法找到它。 - Jon Leopard
错误:首先:文件不存在,这个错误似乎来自迁移容器,您需要检查本地目录结构,它绑定了整个路径“。/迁移”。 - Adiii

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接