When `depends_on` is being used in docker-compose.yml?

Viewed 26

When depends_on is being used in docker-compose.yml?

When a web app has connection to a database, in the docker compose yml file, I see these two examples. One is with depends_on and one is without depends_on.

In one tutorial, I see that there is no depends_on is being used.

version: '3'
services:
  ms-sql-server:
    image: mcr.microsoft.com/mssql/server:2017-latest-ubuntu
    environment:
      ACCEPT_EULA: "Y"
      SA_PASSWORD: "xxxx"
    ports:
      - "1433:1433"
  book-app:
    build: .
    ports: 
      - "8090:80"

In another example, I see that depends_on is being used.

version: "3"
services:
    api:
        build: 
          context: ..
          dockerfile: CF.Api/Dockerfile 
        ports:
            - "8888:80"
        depends_on:
            - db
    db:
        image: "mcr.microsoft.com/mssql/server"
        environment:
            SA_PASSWORD: "xxxx"
            ACCEPT_EULA: "Y"
1 Answers

First, let's understand what depends_on means. The docs:

enter image description here

Based on that description, it's clear that in your second example, namely

version: "3"
services:
    api:
        build: 
          context: ..
          dockerfile: CF.Api/Dockerfile 
        ports:
            - "8888:80"
        depends_on:
            - db
    db:
        image: "mcr.microsoft.com/mssql/server"
        environment:
            SA_PASSWORD: "xxxx"
            ACCEPT_EULA: "Y"

depends_on specifies that the api will need the db, so db as a service needs to be started before api, when docker-compose up is being executed.

Also, if docker-compose api is being executed, that will also start the db service before the api service is started. Also, docker-compose stop will first stop the api and only then stop the db service.

So, first db is started as a service and then api is started as a service as well. Note, that it is possible that api is started before db is ready.

Related