How can we control the startup order of services in Docker compose?

Technology CommunityCategory: DockerHow can we control the startup order of services in Docker compose?
VietMX Staff asked 3 years ago
Problem

I have a container which depends on a redis databse container. However, it takes longer for redis to load in memory which causes the first container to exit. I was wondering if there is a better alternative as I would try to avoid the wait for it script?

You can control the order of service startup and shutdown with the depends_on option that expresses dependency between services. Service dependencies cause the following behaviors:

  • docker-compose up starts services in dependency order. In the following example, db and redis are started before web.
  • docker-compose up SERVICE automatically includes SERVICE’s dependencies. In the following example, docker-compose up web also creates and starts db and redis.
  • docker-compose stop stops services in dependency order. In the following example, web is stopped before db and redis.
version: '3'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

You can also specify a healthcheck in your redis container and add condition: service_healthy to your depends_on field. This works since compose 2.1:

    version: "2.1"
    services:
        web:
        build: .
    ports:
        -"80:8000"
    depends_on:
        "db":
        condition: service_healthy
    command: ["python", "app.py"]
    db:
        image: postgres