【问题标题】:Adminer & Migrate Can't Connect to Postgresql Docker ContainerAdminer & Migrate 无法连接到 Postgresql Docker 容器
【发布时间】:2020-05-04 13:42:23
【问题描述】:

我有三个 docker 容器(postgresql、adminer 和 go/migrate),并且我已经向主机公开了 adminer 和 postgres 端口。我可以在浏览器中访问管理员,postico 也可以连接到数据库。当我尝试从管理员内部连接到数据库时,它会抛出此错误:

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

【问题讨论】:

  • 问题是在迁移容器上没有运行 postgres 服务。本地主机总是指容器本身而不是 docker 主机。将localhost 替换为db

标签: postgresql docker adminer


【解决方案1】:

不需要创建链接,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-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容器找不到它。
  • error: first: file does not exist,这个错误似乎来自于migrate container,你需要检查本地目录结构,它绑定了整个路径.:/migrations
猜你喜欢
  • 2021-08-10
  • 2017-05-04
  • 2019-08-09
  • 1970-01-01
  • 2020-03-24
  • 2019-12-19
  • 2021-04-05
  • 2015-05-01
  • 1970-01-01
相关资源
最近更新 更多