Module 6 Lesson 1: Service Dependencies and Startup Order
·DevOps

Module 6 Lesson 1: Service Dependencies and Startup Order

Master the timing of your stack. Learn how 'depends_on' works and how to use 'wait-for-it' scripts to ensure your app only starts after the database is truly ready.

Module 6 Lesson 1: Service Dependencies

In Module 5, we saw depends_on. But there is a huge "Gotcha": depends_on only waits for the container to Start, not for the software inside to be Ready.

1. The "Race Condition" Problem

  1. Compose: Starts the Postgres container.
  2. Compose: Immediately starts the App container.
  3. Postgres: Takes 5 seconds to initialize its database files.
  4. App: Tries to connect to Postgres immediately, fails, and crashes.

2. Solution A: depends_on with Conditions (V3+)

In modern Docker Compose, you can tell one service to wait for another's Healthcheck.

services:
  app:
    build: .
    depends_on:
      db:
        condition: service_healthy

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

3. Solution B: The "Wait-for-it" Script

If you can't use healthchecks, you can use a wrapper script in your container.

# In your Dockerfile or entrypoint
./wait-for-it.sh db:5432 -- python app.py

This script will loop and try to connect to the DB port. It only runs python app.py once the port is open.


4. Why This Matters

A resilient stack is one that can recover from a total power failure. By setting up proper dependencies, you ensure your stack always "Boots up" correctly without manual intervention.


Exercise: The Boot Race

  1. Create a Compose file with a db (Postgres) and an app (any image that uses ping).
  2. Add a standard depends_on: [db].
  3. Add a command: ["sh", "-c", "ping -c 1 db && echo 'DB is up!'"].
  4. Run docker-compose up. Did the ping work on the very first try?
  5. Now, add the service_healthy condition and a healthcheck to the db.
  6. Run docker-compose up again. Look at the timing. Does the app wait correctly now?

Summary

depends_on is the beginning, but service_healthy is the professional way to manage startup order. By ensuring your services wait for their dependencies to be truly ready, you eliminate "Heisenbugs" from your development and production environments.

Next Lesson: Growing the fleet: Scaling services with 'scale'.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn