In this lesson, you will learn how to orchestrate the order in which your containers start up by using the depends_on directive in your Docker Compose file.
The Problem: Race Conditions
In a multi-tier application, you often have a web service that relies on a database. If you start both containers at the same time, your web application might crash immediately because it tries to connect to a database that hasn't finished initializing its internal processes yet. This is a classic "race condition."
Controlling the Sequence with depends_on
Docker Compose allows you to specify the startup order using the depends_on key. When you include this configuration, Docker ensures that the prerequisite service (like the database) is started before the dependent service (like the web app).
Take a look at this example docker-compose.yml:
services:
database:
image: postgres:latest
web-app:
build: .
depends_on:
- database
In this setup, web-app will wait for database to start.
Important Nuance: "Started" vs "Ready"
It is crucial to understand that depends_on only tracks the container start status. Docker considers the database container "started" as soon as the entrypoint script begins to run. It does not wait for the database engine to finish its internal boot-up (like creating tables or accepting connections).
Because of this, depends_on is a great tool for infrastructure orchestration, but it does not replace the need for "robustness patterns" in your application code, such as implementing retry logic in your web app to wait until the database port is actually accepting traffic. By combining depends_on for container order and retry logic for service availability, you create a stable, predictable deployment.
Key Takeaway: The depends_on directive ensures containers start in a specific sequence, preventing dependency failures during your initial application boot.