Docker Compose Wait til dependency container is fully up before launching

You are probably looking for docker compose healthcheck and the Long Syntax form of depends_on.

The behavior for this feature has changed between docker-copmose versions, so here is the updated way to do so (this docker-compose file works as is):

services:
  db:
    image: postgres
    environment:
      - POSTGRES_USER=king
      - POSTGRES_DB=kong
      - POSTGRES_HOST_AUTH_METHOD=trust
    healthcheck:
      test: pg_isready -U postgres

  web:
    image: alpine
    depends_on: 
      db:
        condition: service_healthy

Then run docker-compose run web, and it will wait for the database before starting.

There is also a more detailed form of the healthcheck directive:

healthcheck:
  test: ["CMD-SHELL", "pg_isready -U postgres"]
  interval: 10s
  timeout: 5s
  retries: 5

Notes:

  1. This requires docker-compose 1.27.0 or higher
  2. In order for this to work, the compose file must not contain version directive (reference)

I've often found using a wait-for-it bash script much more effective than the built in health check to docker-compose.

This runs a TCP health check against a given port and waits until this is complete before starting to run a process.

Sample code:

version: "2"
services:
  web:
    build: .
    ports:
      - "80:8000"
    depends_on:
      - "db"
    command: ["./wait-for-it.sh", "db:5432", "--", "python", "app.py"]
  db:
    image: postgres

Here's some docs:

  • https://docs.docker.com/compose/startup-order/
  • https://github.com/vishnubob/wait-for-it