How to initialize postgres db with flyway in docker?

depends_on of the flyway service does not actually check that the database within db-container is up and running, but instead only checks that the container is up. This is quite different. The container could be up and running at the moment the database within it is starting but not yet accepting connections.

For such a case, you should specify a health check to make sure your database is accepting connections. You can even find an example how to do it with PostgreSQL in the official docker-compose docs.


Version '3+' of the docker-compose file doesn't support parameter condition in the depends_on block, but version '2.1+' does. So you can create compose file like the following, that uses healthcheck from the postgres section, for example:

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