Imagine a small stack: a NestJS API, a PostgreSQL database, and Redis, all started with docker compose up. The API service lists depends_on: [db]. Even so, the API logs ECONNREFUSED on its first query, or exits and restarts a few times before it settles. Sometimes it only happens on a fresh machine, which makes it hard to reproduce.
The Docker Compose startup-order documentation explains why in one sentence: Compose "does not wait until a container is 'ready', only until it's running." A Postgres container is running long before Postgres is accepting connections.
The fix has five parts:
- Give the database a health check that tests what your API actually uses: a TCP connection.
- Make the API wait for it with
condition: service_healthy. - Tune
start_periodandstart_intervalso "healthy" arrives quickly but not falsely. - Give the API its own cheap health check, which works without
curl. - Keep retry and reconnect logic in the application, because startup order does nothing for a database that restarts an hour later.
What depends_on actually waits for
With the short syntax, depends_on: [db] only means "start db first." The Compose services reference says that with the short syntax, Compose doesn't wait for dependencies to be healthy before starting the dependent service.
The long syntax lets you name a condition for each dependency:
service_startedis the default. It's the same as the short syntax: the container has started, and nothing more.service_healthywaits until the dependency'shealthcheckreports healthy. This is the one you want for a database.service_completed_successfullywaits for a one-shot container to exit successfully. It fits a migration job that must finish before the API starts.
A typical layout looks like this:
dbhas a health check.- A
migrateservice depends ondbwithservice_healthy. apidepends ondbwithservice_healthyand onmigratewithservice_completed_successfully.
Startup order also shapes shutdown. Compose stops services in dependency order, so api stops before db. That gives the API a chance to finish in-flight work while the database is still there, which matters if your API handles SIGTERM and shuts down gracefully.
service_healthy only works if the dependency actually has a health check. Defining one is where most of the subtle problems live.
A Postgres health check that tells the truth
The usual check uses pg_isready, which ships in the official postgres image. In Compose you write it as test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]. That's close to the example in Docker's own documentation. Two details are easy to get wrong.
First, the double dollar sign. Compose interpolates variables when it reads the file. A single $POSTGRES_USER is replaced from your host shell or .env file, often with an empty string and a warning. Writing $$ tells Compose to leave a literal $ in place, so the variable is expanded later by the container's shell. That's also why the check uses CMD-SHELL: the plain CMD form runs the command directly, with no shell to expand anything.
Second, on a first boot with an empty data volume, the check can pass too early. On a new volume, the official image's entrypoint runs initdb and any scripts in /docker-entrypoint-initdb.d against a temporary server. It then stops that server and starts the real one. The entrypoint script starts the temporary server with listen_addresses='', so it listens only on the Unix socket inside the container.
That design was deliberate. Pull request #440 in the image repository made the change because pg_isready health checks were marking the container healthy during initialization. The catch is that pg_isready without a host also uses the Unix socket. In issue #880, a maintainer explains that a plain pg_isready will likely connect to the socket, which is available even during initialization, and suggests pg_isready --host 127.0.0.1 to test the TCP port instead.
Put together, a socket-based check can report healthy while the temporary server is still running. Compose then starts your API, and the API's first TCP connection can land in the gap while the temporary server stops and the real one starts. Because initialization only happens when the data directory is empty, this shows up on a fresh clone or a CI runner and not on the next docker compose up. That fits the "fails once, then works" pattern.
The fix is one flag: pg_isready -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB}. Now the check tests the same kind of connection your API makes. During initialization, the TCP port isn't open, so the check keeps failing until the real server is up.
Two more things worth knowing about pg_isready:
- It checks that the server accepts connections, not that your credentials work. The pg_isready documentation says correct user, password, or database values aren't needed to get the status. If they're wrong, the server just logs a failed connection attempt. Pass the right
-Uand-danyway to avoid filling the database log with failures every few seconds. - Its exit codes go beyond 0 and 1. It returns
0when the server is accepting connections,1when it's rejecting them (for example during startup),2when there's no response, and3when no attempt was made. Docker's HEALTHCHECK reference defines0as healthy and1as unhealthy, and reserves2. Appending|| exit 1to the command keeps the result within the codes Docker documents.
Timing: interval, start_period, start_interval, and retries
A health check runs on a schedule, and the defaults are slow for a development stack. According to the Dockerfile reference, as of November 2026 the defaults are:
interval: 30s between checks.timeout: 30s. If a single check runs longer, it counts as a failure and the check process is stopped with SIGKILL.start_period: 0s.start_interval: 5s.retries: 3 consecutive failures before the container is marked unhealthy.
The two start settings work together:
- The start period is a grace window. In
start_period, failures during it don't count towardretries. If a check succeeds during it, the container counts as started, and failures from then on count normally. - The start interval is how often the check runs inside that window. The
start_intervalsetting needs Docker Engine 25.0 or later; Compose added it in version 2.20.2.
Why this matters: with only the default 30-second interval, a database that's ready after two seconds might not be marked healthy until a later check. Everything that waits on service_healthy waits with it. A practical pattern for a local Postgres is a short start_interval (one or two seconds) inside a start_period long enough to cover first-boot initialization, with a relaxed interval afterward. Size the period from your own init scripts; a database that loads a large seed file needs a longer window than an empty one.
A health status starts as starting, becomes healthy after a passing check, and becomes unhealthy after retries consecutive failures.
Redis and other dependencies
The same pattern applies to every dependency your API needs before it can serve requests. For Redis, the common check is redis-cli ping. The Redis PING documentation says it returns PONG normally, and returns an error when the server can't serve data yet, for example while it's loading data from disk.
Be careful about relying on the exit code alone. Whether redis-cli exits non-zero on an error reply can depend on the version and the error, so if you need certainty, check the output for PONG in a CMD-SHELL test. The same caution applies to other databases' "ping" tools: confirm what they actually report before you trust them as a gate.
A health check for the API itself
Your API should have a health check too. It shows up in docker compose ps, and it lets anything that depends on the API, such as a frontend container or an end-to-end test runner, use service_healthy.
The obvious check, curl -f http://localhost:3000/health, is the one Docker's own reference uses as an example. It fails on many Node images because curl isn't there. The official Node image documentation describes the slim variants as containing only the minimal packages needed to run Node. The 22 bookworm-slim Dockerfile installs curl and wget during its build and removes them again. Installing curl just for a health check adds packages, and every extra package is more to keep patched.
You don't need it. Node has had a global fetch without a flag since Node 18, and it has been stable since Node 21 according to the Node.js globals documentation. A health check can call your endpoint with a one-line Node script:
- Use the exec form,
["CMD", "node", "-e", "..."], so it also works in images with no shell, such as distroless images. - The script calls
fetch('http://127.0.0.1:3000/health'), exits0if the response is OK, and exits1on any error. - Set a short
timeout. Each check starts a new Node process, so keep the interval reasonable.
What the endpoint checks matters as much as how you call it. The Kubernetes documentation on liveness, readiness, and startup probes gives a useful vocabulary even outside Kubernetes. A liveness probe decides when to restart a container. A readiness probe decides when it can take traffic, and it may also check required back-end services. Kubernetes also warns that badly designed liveness probes can cause cascading failures.
Docker has a single health status, so decide what it means for your stack:
- For gating dependents in Compose, a readiness-style check is usually what you want. The API is up and can reach its database.
- Keep it cheap. A check that runs a heavy query every few seconds adds steady load. A
SELECT 1or a connection check from your existing pool is usually enough. - Don't let one slow dependency mark everything unhealthy if it isn't required. An optional cache being slow shouldn't block the API from being considered ready.
What restart: true and required: false really do
Two newer depends_on options are often misunderstood.
The restart option covers restarts that Compose performs, not crashes. Added in Compose 2.17.0, restart: true restarts the dependent service after Compose updates or restarts the dependency. The services reference is explicit: it applies to "an explicit restart controlled by a Compose operation," and excludes automated restarts by the container runtime after the container dies. If Postgres crashes and its restart policy brings it back, restart: true doesn't restart your API.
The required option can make a dependency optional. Added in Compose 2.20.0, required: false tells Compose to only warn when the dependency isn't started or available, instead of failing. The default is true. This suits optional services, such as a local mail catcher, that the API can work without.
Restart policies react to exit, not to health. The restart policy documentation describes on-failure and always in terms of the container exiting or stopping. The health status is a signal that Compose and your tools can read, but a container that stays running while unhealthy isn't restarted by those policies. Docker Swarm is different: its services documentation says a task whose container fails health checks is terminated and replaced.
The app still has to retry and reconnect
Health checks and service_healthy fix the startup race. They don't help when the database restarts later because of a crash, an out-of-memory kill, or a host restart. As shown above, restart: true doesn't cover those either. The application has to handle it.
What that looks like depends on your data layer, so check each layer's own behavior instead of assuming it retries:
- NestJS with TypeORM already retries the initial connection. The NestJS TypeORM documentation lists
retryAttempts(default10) andretryDelay(default3000milliseconds), so a slow database gets about 30 seconds by default. AtoRetryfunction can stop retries for errors that won't fix themselves, such as bad credentials, andverboseRetryLogincludes the error in each retry log. These settings are about the initial connection; test how your setup behaves when the database drops after startup. - Prisma connects lazily. The Prisma connection management documentation says the client connects on the first query, or when you call
$connect(). It doesn't document a startup retry, so if you want the API to wait for the database, call$connect()with your own backoff. - Plain node-postgres needs an error listener. The node-postgres Pool documentation says idle clients emit errors when the backend goes down. If the pool emits an
errorevent with no listener, Node raises an uncaught error that can crash your process. A database restart then becomes an API crash, and with a restart policy, a crash loop. Add apool.on('error')handler. Also considerconnectionTimeoutMillis, which defaults to0, meaning no timeout.
This is also where connection limits and shutdown behavior meet. An API that reconnects aggressively after a database restart can exhaust connections, and an API that exits cleanly on SIGTERM makes the reverse-order shutdown above actually useful.
Waiting for healthy services in CI
Integration tests in CI often start a Compose stack and then run tests against it. Starting the tests the moment docker compose up -d returns has the same race as before.
docker compose up --wait handles this. The compose up reference says it waits for services to be running or healthy, and that it implies detached mode. --wait-timeout sets a maximum wait in seconds. Services with a health check are waited on until they're healthy, so your health checks now also gate your test job.
Before depending on it in a pipeline, check how your Compose version reports a service that becomes unhealthy or times out, and make sure the job fails in that case rather than continuing. Release behavior around waiting has changed over time; the Compose release notes are the place to confirm it for your version.
Run migrations the same way you would locally: as a one-shot service with service_completed_successfully, so the tests never see a half-migrated schema.
Old workarounds and old Compose files
If you inherit an older project, you may see a few things that predate today's Compose:
- Wait scripts. The wait-for-it script is a bash script that waits for a TCP host and port. It works, but it needs bash, which many Alpine-based images don't include, and it only proves the port is open. A health check with
service_healthykeeps the waiting logic in the Compose file, where everyone can see it. - A top-level version key. The Compose documentation says the
version:key is only informative and produces a warning that it's obsolete. You can remove it. - Answers saying the condition form doesn't exist. Older answers refer to the version 3 file format, which didn't support the long
depends_onform. Current Compose uses the Compose Specification, which merges the 2.x and 3.x formats, and long-formdepends_onworks. - Docker Swarm. If you deploy the same file with
docker stack deploy, be aware that it still expects the older format and has rejected the long dependency syntax in the past. Swarm doesn't usedepends_onfor ordering anyway.
Checklist
- Wait for health, not just start: use long-form
depends_onwithcondition: service_healthyfor every dependency the API needs at startup. - Check Postgres over TCP:
pg_isready -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB}in aCMD-SHELLtest, with|| exit 1. - Escape container variables: use
$for variables the container should expand, and remember thatCMDhas no shell. - Tune the start window: set
start_periodto cover first-boot initialization and a shortstart_interval(Docker Engine 25.0 or later) so "healthy" arrives quickly. - Check the API without extra packages: use
node -ewithfetchin the exec form instead ofcurl. - Keep the health endpoint cheap, and decide whether it means "alive" or "ready."
- Run migrations as a one-shot service gated by
service_completed_successfully. - Don't expect the restart option to handle database crashes:
restart: truecovers Compose-driven restarts only. - Mark optional services: use
required: false. - Keep retries in the app: TypeORM's retry settings, a backoff around Prisma's
$connect(), or apool.on('error')handler for node-postgres. - Wait in CI: use
docker compose up --wait, and confirm the job fails when a service never becomes healthy. - Test from an empty volume (
docker compose down -v, thenup) so you see the first-boot path your teammates and CI see.



