Controlling Docker Compose Startup Order: depends_on, healthcheck, and Database Readiness

Docker Compose containers are running, but the application cannot connect to its database? Configure depends_on and healthcheck with PostgreSQL, verify service_healthy and up --wait, inspect probe logs, and understand restart recovery limits.

To control startup order in Docker Compose, define a database healthcheck, then make the application wait with condition: service_healthy under depends_on. Using only depends_on: [db] guarantees startup order; database initialization, working credentials, and completed schema migrations each need separate verification.

When a self-hosted service fails on its first deployment but works after manually restarting the application, a common cause is that the database was not ready when the application started. This can also happen after restarting a NAS, restoring a database backup, or changing images.

This article covers Docker Compose V2 and Linux containers, including Docker Desktop in Linux container mode. Documentation was checked on November 7, 2026. The configuration follows official documentation; containers were not started or tested in this article’s environment.

If you have not confirmed variable propagation, first see Troubleshooting Docker Compose environment variables. This article focuses on dependency waits, health checks, and connection verification once the variables are correct.

What running, healthy, and application readiness actually mean

Observation What it establishes What still needs checking
Container is running Its main process is running Whether the service is listening and initialization is complete
Container is healthy Its configured probe recently passed Whether the probe covers the actual failure
Database accepts connections It responds to connection requests Username, password, target database, and permissions
SELECT 1 succeeds This connection can execute simple SQL Schema, migrations, and business transactions
Application page opens An HTTP request receives a response Background jobs, writes, and external dependencies

For example, PostgreSQL may still be recovering or initializing after its main process starts. An application connecting immediately can encounter connection refused or temporary connection rejection.

Adding a fixed sleep 10 only postpones one attempt; it cannot accommodate different disk speeds and data sizes. A better approach is to check dependency status and give the application a way to retry failed connections.

First confirm the Compose version and Docker host

Run these commands in a separate test directory. Do not overwrite an existing production project with the example:

1
2
3
docker compose version
docker context show
docker info

The commands below use docker compose, not the legacy docker-compose. If an option is unrecognized, check the local output of docker compose up --help first.

Pay particular attention to remote Docker contexts: commands run in your local terminal, but containers and volumes may be created on a remote host. Recording the current context helps prevent confusing remote production state with local test results.

Build a minimal example with PostgreSQL and a SQL client

Create an empty directory and save the following as compose.yaml. Here, client executes SQL once and then stays running so you can observe startup dependencies; it is not a business application.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
name: compose-ready-demo

services:
  db:
    image: postgres:17
    environment:
      POSTGRES_USER: demo
      POSTGRES_PASSWORD: local-demo-only
      POSTGRES_DB: demo
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test:
        - CMD-SHELL
        - 'pg_isready -h 127.0.0.1 -U "$${POSTGRES_USER}" -d "$${POSTGRES_DB}"'
      interval: 5s
      timeout: 3s
      retries: 12
      start_period: 20s

  client:
    image: postgres:17
    environment:
      PGHOST: db
      PGPORT: "5432"
      PGUSER: demo
      PGPASSWORD: local-demo-only
      PGDATABASE: demo
    depends_on:
      db:
        condition: service_healthy
        restart: true
    entrypoint: ["/bin/sh", "-ec"]
    command:
      - |
        psql -v ON_ERROR_STOP=1 -c 'SELECT 1 AS connection_ok;'
        exec sleep infinity

volumes:
  pgdata:

The example does not publish the database port to the host. Both containers communicate through the project’s default network; the client uses service name db and container port 5432. Inside a container, localhost generally refers to that container itself, so it cannot replace another service’s name. See Compose networking for the networking rules.

postgres:17 pins the example’s major version; it is not a recommendation to replace an existing database with that version. For production, separately pin a validated image version or digest and plan database upgrades.

The example uses the data directory for PostgreSQL 17. Do not simply switch major versions and reuse the original volume. See the official PostgreSQL image documentation for data directories and initialization variable limitations.

The password here is only for this isolated exercise. Do not use it for a real service or commit it to a public repository. People with Docker administrative access can also inspect environment variables; production credentials should use a secrets mechanism supported by the project.

Why healthcheck and service_healthy are both needed

There are three main dependency conditions:

Condition What it waits for Typical use
service_started The dependency container starts Dependencies that need no internal initialization wait
service_healthy The dependency passes its health check Long-running services such as databases and caches
service_completed_successfully A dependency task exits successfully One-time migrations or initialization jobs

The short form depends_on: [db] cannot express waiting for database health. When you specify service_healthy, the database service must also have a health check it can execute. If the image includes one, verify its coverage rather than assuming it checks every business requirement.

See the Compose services reference for long-form dependency configuration and version requirements.

The probe fields in this example mean:

  • test: The check command executed inside the database container.
  • interval: The normal interval between checks.
  • timeout: The time allowed for each check.
  • retries: The consecutive failure threshold for marking the container unhealthy.
  • start_period: A failure grace period for initialization.

start_period does not enforce a 20-second wait. If the service passes early, it can become healthy early; failures during startup generally do not count toward the failure threshold. Do not simply add these values together and treat the total as a precise readiness guarantee. See Dockerfile HEALTHCHECK for check scheduling and status transitions.

The example explicitly checks the database’s TCP listener at 127.0.0.1. This makes the probe closer to how other containers access the database over TCP, but it still does not cover the network path between containers.

Which layer reads the double dollar sign in the probe?

The $$ in $${POSTGRES_USER} prevents Compose from interpolating the variable early. After Compose parses the configuration, the container’s Shell reads its own POSTGRES_USER.

This uses CMD-SHELL because variable expansion requires a Shell. If you switch to a CMD argument array, do not assume that $VAR will still expand automatically. See the Compose interpolation reference for the rules.

Start the project and verify each layer

First check whether the configuration parses:

1
docker compose config --quiet

To inspect the resolved configuration, run docker compose config, but remember that its output may include passwords. Do not paste unredacted output into public issues or group chats.

Then start the services and wait for their status:

1
2
3
docker compose up --wait --wait-timeout 120
docker compose ps -a
docker compose logs --tail 80 db client

up --wait implies detached mode and waits for services to be running or healthy. A service without a health check only needs to be running; client in this example is such a service. See the docker compose up reference for the options.

The client log should show a connection_ok column with the result 1. This output proves that particular SQL execution succeeded; seeing client running alone does not prove the SQL succeeded.

Next, actively run another query from the client:

1
docker compose exec -T client psql -v ON_ERROR_STOP=1 -c "SELECT current_database(), current_user;"

Both the database and user should be demo. This verifies service-name resolution, networking between containers, database authentication, and a simple query together.

If the application also requires migrations and writes, continue by checking the relevant tables and permissions with its business account. Do not substitute administrator-account test results for acceptance checks using the application’s account.

Why pg_isready cannot prove that the password is correct

pg_isready checks whether the database accepts connections. It does not need the correct username, password, or database name to determine server status. The real application can therefore still fail authentication after the health check passes. See the PostgreSQL pg_isready documentation for this limitation.

Keep “listener ready” and “query succeeded using the application account” as two separate pieces of evidence. If you need a stronger probe, design a lightweight SQL check while controlling its permissions, overhead, and credential exposure.

Inspect the probe output directly when unhealthy

Application logs and health check logs are not stored in the same place. docker compose logs db mainly shows database process output; inspect the container state to see probe results.

In PowerShell, you can read them like this:

1
2
3
4
5
6
7
8
9
$dbContainer = docker compose ps -a -q db
if (-not $dbContainer) {
    throw 'No db container found in this Compose project.'
}
$dbInfo = docker inspect $dbContainer | ConvertFrom-Json
$dbInfo[0].State.Health.Status
$dbInfo[0].State.Health.Log |
    Select-Object Start, End, ExitCode, Output |
    Format-List

The container ID comes from the current Compose project, avoiding manually guessing its name. -a includes exited containers. If no health state exists, first confirm that the service actually has a check configured.

If the database container has exited, prioritize its exit state and main process logs. A database that never started properly cannot be repaired by increasing the health check waiting time.

Probe or application output Check first
command not found Whether the current image contains the probe tool
no response Listening address, port, and whether initialization is still running
rejecting connections Recovery, startup phase, and database logs
password authentication failed Application credentials and existing database users
could not translate host name Service name and network membership
relation does not exist Target database, schema, and migration records

Minimal application images may not include curl, wget, or a Shell. Do not copy another project’s HTTP probe blindly; confirm the tool exists, then check the path, response code, and timeout.

For a PostgreSQL volume that already contains data, changing POSTGRES_PASSWORD does not automatically change an existing user’s password. Follow the database’s account-management procedure; recreating containers or extending start_period will not resolve it.

The two restart settings have different recovery behavior

These two settings are easily confused:

1
2
3
4
5
6
7
services:
  app:
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy
        restart: true

The service-level restart: unless-stopped is a restart policy for container exits. The dependency’s restart: true applies to dependency updates or restarts caused by explicit Compose operations. It excludes automatic restarts by the container runtime after a process crashes.

A database crashing and automatically restarting during operation therefore does not mean Compose will automatically restart every dependent application. A database subsequently becoming unhealthy also does not trigger a container restart policy merely because its health status changed. See Starting containers automatically for exit-based policies.

When the host reboots, Docker Engine starts containers according to restart policies; you cannot assume the complete Compose dependency wait runs again. Applications still need to handle lost connections, resolve service names again, and rebuild connection pools.

This example deliberately has no service-level automatic restart policy so you can observe the result of a single startup. When adapting it for production, design recovery from process exits and recovery from database disconnections separately.

How to verify an explicit dependency restart

Run this only in the isolated example:

1
2
3
docker compose restart db
docker compose logs --since 2m db client
docker compose exec -T client psql -v ON_ERROR_STOP=1 -c "SELECT 1;"

Observe whether the client executes its startup command again, and check whether the latest query succeeds. Do not treat this experiment as proof that every database failure recovers automatically. Also do not treat restart as a readiness acceptance procedure identical to the first up.

Migrations must finish separately after the database is healthy

If application startup depends on its database schema, make migration an explicit one-time task. The dependency chain can be: database healthy → migration exits successfully → application starts.

The key dependency condition is:

1
2
3
depends_on:
  migrate:
    condition: service_completed_successfully

This is only a fragment inside the application service, not a standalone configuration; it still needs the project’s real migrate service. Use the application’s officially supported migration command, and ensure failure returns a nonzero exit code. Do not hide migration failures with || true, or put writes and migrations into a recurring health check.

After a schema change, rolling back the application image may not roll back the database schema. Check migration compatibility and the backup recovery plan before deployment.

Apply check changes and finish the exercise

After saving compose.yaml, validate it and apply it:

1
2
docker compose config --quiet
docker compose up --wait --wait-timeout 120

Running only docker compose restart will not apply newly written container configuration. If a check fails, first preserve the logs, restore a previously validated configuration, then apply it with up. If the database itself cannot start, move to database recovery rather than repeatedly recreating containers and obscuring the diagnosis.

To finish this example, run:

1
docker compose down

This removes the project’s containers and default network while keeping the example’s named data volume. Do not simply add -v to fix readiness failures; it would delete the database volume declared in the example. If disk space is low, first use the Docker disk space cleanup guide to establish what owns the data.

Frequently asked questions

Does a successful up –wait mean the website is usable?

No. Only services with suitable health checks are assessed using those probes. Also check HTTP, login, database reads and writes, and required background jobs through the actual access point.

Can docker compose wait wait for database health?

No. docker compose wait waits for the specified service containers to stop; it serves a different purpose from startup’s up --wait. See the docker compose wait reference.

Why not just set retries to a very large number?

More retries can help with confirmed slow initialization. For incorrect passwords, wrong service names, missing tools, and failed migrations, they only delay the error. Read the specific output before adjusting the waiting budget.

Can this be used directly with docker stack deploy?

This article covers local or remote Docker projects managed with Compose V2. Do not directly apply these dependency waits to a Swarm stack; verify the deployment platform’s supported configuration and readiness mechanisms separately.