How to start service only when other service had completed?

This is a supplement to @zooblin ‘s answer

Since docker-compose version 1.29, we can do it by condition: service_completed_successfully

In your scene, database service start will cost some time, so the migration scripts should be executed after database fully started.

And the application service should start after migration scripts executed successfully.

the docker-compose.yaml may be like following(here we use cassandra as exmaple, for other database, you can just modify healthcheck commands):

version: '3.8'
services:
  applicaion-service:
    image: your-applicaion-service:0.0.1
    depends_on:
      cassandra-init-keyspace:
        condition: service_completed_successfully


  cassandra:
    image: cassandra:4.0.1
    ports:
      - "9042:9042"
    healthcheck:
      test: ["CMD", "cqlsh", "-u cassandra", "-p cassandra" ,"-e describe keyspaces"]
      interval: 15s
      timeout: 10s
      retries: 10

  cassandra-init-keyspace:
    image: cassandra:4.0.1
    depends_on:
      cassandra:
        condition: service_healthy
    volumes:
      - ./src/main/resources/cassandra/init.cql:/init.cql
    command: /bin/bash -c "echo loading cassandra keyspace && cqlsh cassandra -f /init.cql"

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)