【问题标题】:How to initialize postgres db with flyway in docker?如何在docker中使用flyway初始化postgres db?
【发布时间】:2019-01-31 23:58:47
【问题描述】:

我有 django 应用程序,我试图在 docker 中托管。在启动 django 应用程序之前,我未能成功启动我的 postgres 服务器。这是我的docker-compose.yaml

version: '3'
services:
  flyway:
    image: boxfuse/flyway
    command: -url=jdbc:postgresql://db/dbname -schemas=schemaName -user=user -password=pwd migrate
    volumes:
      - ./flyway:/flyway/sql
    depends_on:
      - db
  db:
    image: postgres:9.6
    restart: always
    ports:
      - 5432:5432
    environment:
    - POSTGRES_PASSWORD=pwd
    healthcheck:
      test: "pg_isready -q -U postgres"
  app:
    image: myimage
    ports:
      - 8000:8000

dbapp 服务似乎都很好,但我无法使用 flyway 启动 postgres 默认值。以下是我遇到的错误:

flyway_1  | SEVERE: Connection error: 
flyway_1  | org.postgresql.util.PSQLException: Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

ERROR: 
flyway_1  | Unable to obtain connection from database (jdbc:postgresql://db/dbname) for user 'user': Connection to db:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

我找不到一个很好的例子来说明如何将 flyway 与 Postgres 一起使用。我该如何让它发挥作用? TIA

【问题讨论】:

    标签: postgresql docker-compose flyway


    【解决方案1】:

    flyway 服务的depends_on 实际上并不检查 db-container 中的数据库是否已启动并正在运行,而只是检查容器是否已启动。这是完全不同的。容器可能在其中的数据库正在启动但尚未接受连接时启动并运行。

    对于这种情况,您应该指定健康检查以确保您的数据库正在接受连接。您甚至可以在 official docker-compose docs 中找到如何使用 PostgreSQL 进行此操作的示例。

    【讨论】:

    • 感谢您的指出,我设法通过docker-compose up 为每个服务按所需顺序解决了这个问题。这似乎消除了依赖问题。
    【解决方案2】:

    depends_on 块中 docker-compose 文件 doesn't support 参数 condition 的版本“3+”,但版本“2.1+”does。因此,您可以创建如下组合文件,该文件使用 postgres 部分中的 healthcheck,例如:

    version: '2.1'
    
    services:
      my-app:
    #   ...  
    #   ... 
        depends_on:
          - flyway
    
      flyway:
        image: boxfuse/flyway:5-alpine
        command: -url=jdbc:postgresql://postgres:5432/mydb -schemas=public -user=postgres -password=postgres migrate
        volumes:
          - ./migration:/flyway/sql
        depends_on:
          postgres:
            condition: service_healthy
    
      postgres:
        domainname: postgres
        build: ./migration
        ports:
          - "5432:5432"
        environment:
          - POSTGRES_USER=postgres
          - POSTGRES_PASSWORD=postgres
        healthcheck:
          test: ["CMD", "pg_isready", "-q", "-U", "postgres"]
          interval: 5s
          timeout: 1s
          retries: 2
    

    【讨论】:

      【解决方案3】:

      请使用-connectRetries 等待postgres,例如(等待60s):-connectRetries=60

      更多细节在这里 https://github.com/flyway/flyway-docker

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-25
        • 2023-03-12
        • 2013-02-27
        • 1970-01-01
        相关资源
        最近更新 更多