LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
Docker

Managing Startup Order with Depends_On

When building microservices, we often run multiple containers at the same time using Docker Compose. A common scenario is starting a backend API alongside a database like PostgreSQL or Redis. But here is the problem: a lightweight API starts in less than a second, while a database might take five to ten seconds to allocate memory and accept connections. If the API tries to connect before the database is ready, the API crashes.

Managing Startup Order with Depends_On

When building microservices, we often run multiple containers at the same time using Docker Compose. A common scenario is starting a backend API alongside a database like PostgreSQL or Redis. But here is the problem: a lightweight API starts in less than a second, while a database might take five to ten seconds to allocate memory and accept connections. If the API tries to connect before the database is ready, the API crashes.

To fix this race condition, we must explicitly tell Docker Compose not just to start the database first, but to wait until the database is actually healthy and ready for traffic before booting up the API.

What you will learn
  • The fatal flaw in using basic depends_on without conditions.
  • How to write a robust healthcheck for your database containers.
  • How to use condition: service_healthy to orchestrate perfect startup sequences.

1. The Problem with Default Startup Orders

By default, when you run docker compose up, it tries to start all your containers at the exact same time to save time. If you add a basic depends_on block to your API, Docker Compose will wait to start the API until the database container is created. However, a container being "created" or "running" does not mean the software inside it is ready to accept connections.

To gain precise control, Docker Compose offers three different conditions for the depends_on property.

Condition What it means When to use it
service_started Waits only until the dependency container is running. (This is the default). condition: service_started
service_healthy Waits until the dependency container passes its defined health check script. condition: service_healthy
service_completed_successfully Waits for a one-off task container to finish its job and exit cleanly. condition: service_completed_successfully

2. Implementing Health Checks and Depends_On

To use service_healthy, we must first tell Docker how to check if the database is actually ready. We do this using the healthcheck block. For PostgreSQL, we can use its built-in utility called pg_isready.

Writing the Docker Compose File

Example 1: docker-compose.yml

services:
  db:
    image: postgres:15-alpine
    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: secretpassword
      POSTGRES_DB: userdb
    # 1. Define how to check if Postgres is ready
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U admin -d userdb"]
      interval: 5s
      timeout: 5s
      retries: 5

  api:
    image: my-backend-api:latest
    ports:
      - "5000:5000"
    # 2. Tell the API to wait for the DB to be healthy
    depends_on:
      db:
        condition: service_healthy

Expected output during "docker compose up"

[+] Running 2/2
 ✔ Container project-db-1   Healthy    5.2s 
 ✔ Container project-api-1  Started    5.4s 
Important: If the health check fails after all retries (e.g., 5 retries spaced 5 seconds apart), the database container will be marked as "unhealthy", and the API container will never start. This protects your system from booting into a broken state.

3. Architecture / Workflow Visualized

Here is what happens under the hood when Docker Compose processes this orchestrated startup sequence.

Docker Compose Orchestration Flow

Docker Compose PostgreSQL (DB) Healthcheck: pg_isready Backend API Waiting for DB... condition: healthy

The database starts first. The API container pauses its creation until the database's internal health check returns a success signal.

4. Step-by-Step Execution Breakdown

When you type docker compose up, here is the exact sequence of events managed by the Docker engine:

Step 1: Parsing the Tree: Docker reads the YAML file and builds a dependency tree. It sees that api depends on db.
Step 2: Database Initialization: Docker starts the db container. The container state becomes "running", but its health state is "starting".
Step 3: Polling Health: Docker waits the defined interval (5 seconds), then runs pg_isready inside the database container. If Postgres is still allocating memory, it fails. Docker waits and tries again.
Step 4: Success Signal: Once pg_isready succeeds (returns a 0 exit code), Docker changes the database state to "healthy".
Step 5: API Boot: Only after the "healthy" state is achieved does Docker finally create and start the api container. The API connects immediately without crashing.
Watch out: Do not rely on basic sleep 10 commands inside your API code to wait for the database. Hardcoded wait times break easily if the server is under heavy load and the database takes 12 seconds to boot instead of 10.

5. Hands-On Practice

Test your orchestration skills by implementing health checks for different types of dependencies.

Beginner Exercise 1: Basic Dependency

You have a frontend service and a backend service. The backend does not have a health check defined. How do you make the frontend start after the backend?

Hint: Use depends_on without any extra conditions, which defaults to service_started.

Intermediate Exercise 2: Redis Health Check

You are using a Redis caching container. Write a health check for the Redis image and make your API wait for it.

Expected result: You should define a healthcheck block using the command redis-cli ping, and use condition: service_healthy on the API.

Advanced Exercise 3: Database Migrations

You have three containers: db (Postgres), migrate (a short-lived script that creates tables), and api. The API requires the tables to exist.

Hint: The migrate container should wait for db to be service_healthy. The api container should wait for the migrate container using condition: service_completed_successfully.

6. Interview Questions

If you are applying for backend, DevOps, or Full-Stack roles, you will likely be asked about container lifecycle management.

Q1. Why does my application crash on startup even though I added "depends_on: db" in my Docker Compose file?

Answer: Because standard depends_on only waits for the database container to be created and running, not for the database software inside it to be ready to accept connections. The application attempts to connect while the database engine is still initializing, resulting in a connection refused error.

Q2. How do you ensure a database is actually ready before an API starts in Docker Compose?

Answer: By defining a healthcheck block on the database service that runs a readiness command (like pg_isready or mysqladmin ping), and then updating the API's depends_on block to use condition: service_healthy.

Conclusion

Relying on luck or hardcoded sleep timers for your microservices to start is a recipe for flaky deployments and frustrating debugging sessions. By implementing proper health checks and utilizing the extended features of depends_on, you ensure your architecture boots up predictably and reliably every single time, whether on your local machine or in a production AWS environment.

Official Documentation

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.