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
- Compose: Starts the Postgres container.
- Compose: Immediately starts the App container.
- Postgres: Takes 5 seconds to initialize its database files.
- 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
- Create a Compose file with a
db(Postgres) and anapp(any image that usesping). - Add a standard
depends_on: [db]. - Add a
command: ["sh", "-c", "ping -c 1 db && echo 'DB is up!'"]. - Run
docker-compose up. Did the ping work on the very first try? - Now, add the
service_healthycondition and a healthcheck to thedb. - Run
docker-compose upagain. Look at the timing. Does theappwait 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'.