Home DockerDocker Compose Depends_on: Fix Container Startup Order

Docker Compose Depends_on: Fix Container Startup Order

by Knowledge Base Linux
Docker Compose depends_on startup order diagram for containers

If you have ever watched a web container crash on startup because the database was not ready yet, you have already met the problem that Docker Compose depends_on is designed to solve. The confusion is that depends_on sounds like a guarantee, but in its simplest form it only controls the order in which containers start, not whether the dependency is actually ready to accept connections. This guide explains the difference between starting and being ready, shows the short and long syntaxes with real examples, and walks through a complete web, database, and cache stack that starts reliably every time. By the end you will know exactly when depends_on is enough, when you need a healthcheck, and what to do when the ordering still goes wrong.

The core idea is simple: Docker Compose starts services in dependency order, but a container that has started is not necessarily a service that is usable. A PostgreSQL container can be running for several seconds before it finishes initialisation and accepts connections, and a web application that connects during that window will fail, retry a few times, and often exit before the database is ready. Restart policies can mask this problem, but they turn a clean startup into a flapping mess of crash loops and confusing logs. The correct fix is to make Compose wait for readiness, not just for process start, and that is what the long syntax of depends_on combined with healthchecks achieves. If you are still getting comfortable with Compose fundamentals, our Docker Compose healthchecks guide is a useful companion to this article.

Docker Compose depends_on healthcheck example with database service

Prerequisites

You need Docker Engine and Docker Compose v2 installed on a Linux host, plus a basic compose file you can experiment with. All examples in this article use the Compose Specification format supported by Compose v2, which is the version you get from the docker compose command today. You should also be comfortable running docker compose up, docker compose ps, and docker compose logs, because the troubleshooting section relies on those commands. No swarm cluster or registry is needed: everything here runs on a single host. The examples use PostgreSQL and Redis images, but the patterns apply identically to MySQL, MariaDB, RabbitMQ, and any other dependency that needs time to become ready.

How Docker Compose depends_on Works

The short syntax is a list of service names, and it guarantees start order only. In the example below, Compose starts db before web, but it does not wait for PostgreSQL to finish initialising. If the web service connects immediately, it may fail. The short syntax is still useful when the dependency starts instantly or when the dependent service already retries connections gracefully, but it is not a readiness guarantee and should never be treated as one.

services:
  web:
    build: .
    depends_on:
      - db
  db:
    image: postgres:16

The long syntax, by contrast, lets you attach a condition to each dependency. There are three conditions, and choosing the right one is the whole skill. The service_started condition behaves like the short syntax: it waits only for the container to start. The service_healthy condition waits until the dependency reports healthy, which requires that dependency to define a healthcheck. The service_completed_successfully condition waits until a container exits with status code zero, which is designed for one-shot tasks such as database migrations or seed jobs that must finish before the application starts. Most real stacks need service_healthy for databases and caches, and service_completed_successfully for migration jobs.

Docker Compose depends_on Long Syntax with Healthchecks

A healthcheck is a command that Compose runs inside the container at intervals to decide whether the service is healthy. For PostgreSQL, the pg_isready utility is the natural choice because it is shipped in the image and reports precisely whether the server accepts connections. For MySQL, mysqladmin ping serves the same purpose. The healthcheck below waits five seconds before the first check, then probes every five seconds, allowing up to five seconds per probe and five retries before marking the container unhealthy. Those numbers are a reasonable starting point; slow disks or large initialisation scripts may need a longer start period.

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: appuser
      POSTGRES_PASSWORD: secretpassword
      POSTGRES_DB: appdb
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U appuser -d appdb"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 10s
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy

Notice that the condition lives under the dependency name, not as a flat list entry. This is the single most common syntax mistake, and Compose will reject the file with an error if you mix the two forms. With this configuration, Compose starts the database, runs the healthcheck until it passes, and only then starts the web service. The web service still benefits from its own connection retry logic as a safety net, because a healthy check and a successful application connection are not quite the same thing, but the race window shrinks from seconds to almost nothing. The official Docker documentation on controlling startup order in Compose describes the same conditions and their limitations.

A Complete Web, Database, and Cache Example

Real applications rarely have a single dependency. A typical stack has a web service that needs both a database and a cache, plus a migration job that must run before the web service serves traffic. The compose file below combines all three conditions in one place: the web service waits for the database and the cache to be healthy, and for the migration job to complete successfully. The migration service uses the same image as the web service but overrides the command, which keeps the image count low and guarantees the migration code matches the application code exactly.

services:
  web:
    build: .
    ports:
      - "8000:8000"
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_healthy
      migrate:
        condition: service_completed_successfully
  migrate:
    build: .
    command: python manage.py migrate
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:16
    environment:
      POSTGRES_USER: appuser
      POSTGRES_PASSWORD: secretpassword
      POSTGRES_DB: appdb
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U appuser -d appdb"]
      interval: 5s
      timeout: 5s
      retries: 5
  cache:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5
volumes:
  pgdata:

Start the stack with docker compose up and watch the order: the database and cache start first, the migration runs once they are healthy, and the web service starts last. Verify the state with docker compose ps, which shows the health status of each service, and confirm the migration actually ran by checking its logs. If you stop and restart the stack, the migration runs again, which is fine for idempotent migrations but worth noting if your migration tool is not safe to re-run. For a deeper look at how volumes interact with this kind of stack, see our comparison of Docker volumes versus bind mounts.

Restart Pitfalls and the Swarm Caveat

Restart policies interact with depends_on in ways that surprise people. A restart policy of unless-stopped on the web service means that if the database container restarts, the web service does not automatically restart with it, because depends_on only applies at initial startup, not to later restarts. If your database restarts and the web service holds a dead connection pool, the application may keep failing until you restart it manually. The robust answer is application-level reconnection logic: the application should retry failed database connections with backoff rather than assuming the connection it opened at boot will live forever. Compose ordering solves startup; it does not solve runtime resilience.

There is also an important deployment caveat. When you deploy a compose file as a swarm stack, the long syntax of depends_on is ignored, because swarm mode does not support startup ordering conditions. Swarm users need a different strategy, typically an entrypoint wrapper script that waits for the dependency, or an application that retries connections until the dependency appears. If you only ever run docker compose up on a single host, this does not affect you, but it is the reason you should never assume a compose file behaves identically in every deployment target. Always check which Compose features your target supports before relying on them.

Troubleshooting

When a service stays unhealthy, start with docker compose ps to see the health status, then docker compose logs for the failing service. An unhealthy database usually means the healthcheck itself is wrong: the most common mistake is checking with the wrong username or database name, so pg_isready fails even though PostgreSQL is running fine. Test the healthcheck command manually by running it inside the container with docker compose exec, and adjust the credentials until it passes. If the healthcheck passes manually but the container still reports unhealthy, check the interval and start period: a database doing crash recovery on a large dataset may need a start period of thirty seconds or more.

Restart loops have a different signature: the dependent service starts, crashes with a connection error, restarts, and crashes again. Check whether the dependency is actually healthy at the moment of the crash, and look at the application logs for the exact connection error rather than guessing. If the application connects to the wrong hostname, no amount of depends_on tuning will help, because the service name in the compose file is the DNS name the application must use. Also confirm that the dependent service is not starting before the dependency at all: a typo in the service name under depends_on produces an error at compose up time, but a dependency listed under the wrong service is silently valid and simply does nothing useful.

Finally, if depends_on appears to be ignored entirely, verify that you are running Compose v2 and that the file uses the services top-level key without an obsolete version key. Very old compose files that declare version 2 with a different condition syntax can confuse the parser, and the fix is to modernise the file to the current Compose Specification format. When in doubt, run docker compose config to print the fully resolved file and confirm that the conditions appear exactly as you wrote them.

Conclusion

Depends_on is a startup ordering tool, not a readiness guarantee, and the distinction matters. Use the short syntax when start order is genuinely all you need, use the long syntax with service_healthy for databases and caches, and use service_completed_successfully for migration and seed jobs that must finish first. Pair ordering with healthchecks, keep application-level reconnection logic as your safety net, and remember the swarm caveat before you deploy the same file elsewhere. With those pieces in place, your stack will start in the right order, wait for the right things, and stop waking you up with crash loops at three in the morning.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.