Docker Compose Healthchecks: How to Make Services Wait for Postgres
A practical guide to Docker Compose healthchecks, depends_on service_healthy, start_interval, healthchecks without curl, and debugging unhealthy containers.
tags: docker, devops, tutorial, webdev
cover_image:
Docker Compose Healthchecks: How to Make Services Wait for Postgres, Redis and Your API
You run docker compose up, your API container starts, tries to connect to Postgres, and crashes with ECONNREFUSED or connection refused. You run it again and it works. You run it in CI and it fails one time out of five.
If that sounds familiar, the problem is not your code. It is the gap between a container being started and a service being ready. Docker Compose has a clean, built-in solution for that gap: healthchecks combined with the long form of depends_on.
This guide covers everything you need to use them well:
• Why depends_on on its own does not wait for your database
• How a healthcheck works, option by option, including the newer start_interval
• The depends_on conditions service_healthy, service_started and service_completed_successfully
• Copy-paste healthchecks for PostgreSQL, MySQL, MariaDB, Redis, MongoDB, RabbitMQ, Elasticsearch and your own API
• How to write a healthcheck without curl, for Alpine and distroless images
• How to debug a container stuck in unhealthy
• How to use docker compose up --wait in CI pipelines
• What healthchecks do and do not do in production
Every example uses the current Compose Specification, so there is no version: key at the top of the files. If you still have version: "3.8" in your docker-compose.yml, you can delete it: modern Docker Compose ignores it and prints a warning.
TL;DR
If you only have two minutes, this is the pattern:
services:
db:
image: postgres:17
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: appdb
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
api:
build: .
depends_on:
db:
condition: service_healthy
The db service reports its own health. The api service waits until db is healthy before Compose starts it. No wait-for-it.sh, no sleep 10, no retry loop in your entrypoint.
The rest of this article explains why each line is there and how to adapt it to every other service in your stack.
Why depends_on Alone Doesn't Wait for Your Database
This is the most common misunderstanding about Docker Compose, so it is worth being precise about it.
Started Is Not the Same as Ready
When you write the short form:
services:
api:
build: .
depends_on:
- db
db:
image: postgres:17
Compose guarantees exactly one thing: it creates and starts the db container before it starts the api container. That's all.
"Started" means the container's main process is running. For PostgreSQL, the process is running long before it accepts connections. On first boot, the official image initialises the data directory, runs any scripts in /docker-entrypoint-initdb.d/, creates your user and database, shuts down a temporary server and then starts the real one. That can take anywhere from one second to more than a minute, depending on your machine and your init scripts.
Your API starts the moment the Postgres container's process is running. If your API opens a database connection at boot, it races against Postgres's startup, and sometimes it loses.
What the Race Condition Looks Like in Practice
The symptoms depend on your stack, but they usually look like one of these:
Error: connect ECONNREFUSED 172.18.0.2:5432
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "db" (172.18.0.2), port 5432 failed: Connection refused
FATAL: the database system is starting up
The last one is a good example of why "the port is open" is not good enough either. Postgres can accept TCP connections and still refuse queries while it is starting up or recovering.
The bug is intermittent because the result depends on timing. On your fast laptop with a warm image cache, Postgres usually wins. On a shared CI runner, under load, with a fresh volume, it often loses. That's why so many teams end up with a "flaky" integration test suite that is really just a startup ordering problem.
A Short History: v2, v3 and the Compose Specification
If you have searched for this before, you may have found conflicting answers. Here is why.
Compose file format v2
The v2 file format supported depends_on with a condition: service_healthy. It worked, and many people used it.
Compose file format v3
The v3 format was designed to be compatible with Docker Swarm, and the condition option was removed. The official advice at the time was to make your application resilient to dependencies being unavailable, and to use scripts like wait-for-it.sh or dockerize for startup ordering. Many old Stack Overflow answers date from this period.
The Compose Specification
Docker Compose v2 (the docker compose plugin, written in Go) implements the Compose Specification, which merged the v2 and v3 formats and brought condition back. Today, depends_on with condition: service_healthy is fully supported, and it is the cleanest way to solve startup ordering in Compose.
The advice from the v3 era is still partly true: your application should handle a dependency going away at runtime. But for startup ordering, healthchecks are the right tool.
Anatomy of a Docker Compose Healthcheck
A healthcheck is a command Docker runs inside the container on a schedule. The command's exit code decides whether the container is healthy. Here is the full set of options:
healthcheck:
test: ["CMD-SHELL", "curl -fs http://127.0.0.1:3000/health || exit 1"]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s
start_interval: 2s
disable: false
The test Command
The test option is the actual check. It runs inside the container, not on your host. This is the single most important thing to remember, because it explains most healthcheck bugs:
• localhost means the container itself, not your machine.
• The binary you call (curl, wget, pg_isready) must exist inside the image.
• Environment variables are the container's variables, not your shell's.
CMD vs CMD-SHELL
There are three forms for test:
1. Exec form: runs the binary directly, no shell
test: ["CMD", "pg_isready", "-U", "app"]
2. Shell form: runs through /bin/sh -c
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} || exit 1"]
3. Plain string: same as CMD-SHELL
test: pg_isready -U app
Use CMD when you have a single command with fixed arguments. It doesn't need a shell, so it works in minimal images that have no /bin/sh.
Use CMD-SHELL when you need shell features: environment variable expansion, pipes, ||, && or redirection. This requires /bin/sh in the image.
There is also a fourth value, ["NONE"], which disables any healthcheck inherited from the image. The disable: true option does the same thing and is easier to read.
Exit Codes
Docker only cares about the exit code of your command:
Exit code Meaning
0 Healthy
1 Unhealthy
2 Reserved, do not use
Any command that may return something other than 0 or 1 should be wrapped with || exit 1. For example, curl -f returns 22 on an HTTP error, so curl -f http://... || exit 1 normalises it to 1. In practice, Docker treats any non-zero code as a failure, but sticking to 0 and 1 keeps you inside the documented behaviour.
Timing Options
Timing is where most healthchecks go wrong. Too slow, and your stack takes forever to start. Too aggressive, and you mark a perfectly fine service as unhealthy during a slow boot.
interval, timeout and retries
• interval (default 30s): how long Docker waits between checks once the container is running.
• timeout (default 30s): how long a single check may run before it counts as failed.
• retries (default 3): how many consecutive failures it takes to mark the container unhealthy.
The defaults are designed for long-running production services, not for local development. With a 30-second interval, a dependent service may wait up to 30 seconds after the database is actually ready before it starts. For local stacks, interval: 5s or 10s is a better choice.
A good rule of thumb: timeout should be well below interval, and interval × retries should be longer than any normal hiccup your service might have (a garbage collection pause, a brief load spike), so you don't flap between healthy and unhealthy.
start_period and start_interval
start_period (default 0s) is a grace period for slow-starting containers. During this window, failed checks do not count towards retries. If a check succeeds during the start period, the container becomes healthy immediately and the start period ends.
This is perfect for databases that run init scripts, JVM applications that take 40 seconds to warm up, or anything that downloads a model at boot.
start_interval is the newer, lesser-known option, and it fixes an annoying trade-off. Before it existed, you had to choose:
• A short interval so the container turns healthy quickly at startup, which means you also run the check very often forever after.
• A long interval to save resources at runtime, which means dependent services wait longer at startup.
start_interval sets a separate, faster check frequency that only applies during the start_period. Once the start period ends, Docker switches to the normal interval.
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U app"]
start_period: 60s
start_interval: 1s # check every second while booting
interval: 30s # then every 30 seconds
timeout: 5s
retries: 3
With this setup, your database is detected as ready within about a second of becoming ready, but at runtime it is only probed twice a minute.
start_interval requires Docker Engine 25.0 or newer. Run docker version to check what you have. If your CI runners or production hosts run an older engine, leave it out.
The Three Health States
A container with a healthcheck is always in one of three states, which you can see in docker ps or docker compose ps:
• starting: the container is running, but no check has succeeded yet and it hasn't failed enough times to be unhealthy.
• healthy: the most recent check succeeded.
• unhealthy: the check has failed retries times in a row (outside the start period).
A container without a healthcheck has no health state at all. That matters for depends_on, as you'll see next: you can't wait for service_healthy on a service that has no healthcheck defined. Compose will refuse to start the stack with an error.
The depends_on Long Syntax: service_healthy Example and More
The short form of depends_on is a list. The long form is a map, where each dependency gets its own options:
services:
api:
build: .
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
migrate:
condition: service_completed_successfully
There are three conditions.
service_started
This is the default and the same as the short form. Compose waits until the dependency's container has started. Use it for dependencies that your service can tolerate being briefly unavailable, or that have no meaningful readiness signal.
service_healthy
Compose waits until the dependency reports healthy. If the dependency becomes unhealthy instead, Compose stops and returns an error like:
dependency failed to start: container myapp-db-1 is unhealthy
This is the condition you want for databases, caches, message brokers and any API your service calls at startup.
service_completed_successfully: The Migrations Pattern
This condition waits for the dependency to run and exit with code 0. It is made for one-off tasks: database migrations, seeding, building assets, generating config files.
Here is a clean and common setup for running migrations before your API starts:
services:
db:
image: postgres:17
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: appdb
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U app -d appdb"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
start_interval: 1s
migrate:
build: .
command: ["npm", "run", "migrate"]
environment:
DATABASE_URL: postgres://app:secret@db:5432/appdb
depends_on:
db:
condition: service_healthy
api:
build: .
command: ["npm", "start"]
environment:
DATABASE_URL: postgres://app:secret@db:5432/appdb
depends_on:
db:
condition: service_healthy
migrate:
condition: service_completed_successfully
The order is now explicit and enforced:
- db starts and becomes healthy.
- migrate starts, runs migrations and exits with 0.
- api starts against a database that is up and has the right schema.
If the migration fails, api never starts, and Compose tells you exactly which dependency failed. That is much easier to debug than an API that boots and then throws relation "users" does not exist on the first request.
The same pattern works for Django (python manage.py migrate), Rails (bin/rails db:migrate), Prisma (npx prisma migrate deploy), Alembic (alembic upgrade head), Flyway, Liquibase and every other migration tool.
restart: true and required: false
Two newer options round out the long syntax.
restart: true
depends_on:
db:
condition: service_healthy
restart: true
With restart: true, when Compose restarts the dependency as part of a Compose operation (for example docker compose restart db, or a recreation after you change its config), it also restarts the dependent service. This is useful for apps that open a connection pool at boot and don't reconnect well. It requires Docker Compose 2.17 or newer.
Note the limitation: this only applies to restarts that Compose itself performs. If the database container crashes and is restarted by Docker's restart policy, Compose isn't involved, and your API won't be restarted.
required: false
depends_on:
mailhog:
condition: service_started
required: false
With required: false, Compose only warns if the dependency isn't running or isn't part of the project, instead of failing. This is handy with Compose profiles, where some services (like a local mail catcher or a debug tool) are only enabled for some developers. It requires Docker Compose 2.20 or newer.
Copy-Paste Healthchecks for Popular Services
These are tested-style patterns for the services that show up in almost every Compose stack. Adjust users, passwords and ports to your setup.
A note on the $$ you'll see in several examples: Compose interpolates $VAR from your host's environment and .env file when it reads the file. Writing $$VAR escapes it, so the literal $VAR reaches the container, where the shell expands it using the container's environment. Use $$ when you want the container's variables, which is almost always what you want inside a healthcheck.
PostgreSQL: pg_isready Docker Compose Healthcheck
db:
image: postgres:17
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: appdb
healthcheck:
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
start_interval: 1s
pg_isready ships with the official Postgres image and checks whether the server is accepting connections. It returns 0 when it is, 1 when the server is rejecting connections (for example, during startup), and 2 when there is no response.
Avoid the Init-Time False Positive
Why -h 127.0.0.1? During first-boot initialisation, the official image starts a temporary Postgres server that only listens on a Unix socket, runs your init scripts, then shuts it down and starts the real server on TCP. If your healthcheck uses the default Unix socket, it can report healthy while that temporary server is running. Your API then starts, connects over TCP to db:5432, and finds nothing there.
Forcing the check over TCP with -h 127.0.0.1 means it only succeeds once the real server is listening on the network, the same way your application connects.
Checking That Queries Actually Work
pg_isready doesn't log in or run a query. If you want a stricter check, for example to confirm that your user and database exist, use psql:
healthcheck:
test: ["CMD-SHELL", "psql -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB} -c 'SELECT 1' || exit 1"]
Since this connects from inside the container, the image's default local trust rules usually let it in without a password. If you've changed pg_hba.conf or POSTGRES_HOST_AUTH_METHOD, set PGPASSWORD in the container's environment.
MySQL and MariaDB
For MySQL:
mysql:
image: mysql:8.4
environment:
MYSQL_ROOT_PASSWORD: rootsecret
MYSQL_DATABASE: appdb
MYSQL_USER: app
MYSQL_PASSWORD: secret
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -u root -p$${MYSQL_ROOT_PASSWORD} --silent"]
interval: 10s
timeout: 5s
retries: 5
start_period: 60s
start_interval: 2s
The -h 127.0.0.1 trick matters here for the same reason as with Postgres: during initialisation, the MySQL image runs a temporary server with networking disabled. Checking over TCP avoids marking the container healthy too early.
MySQL's first boot is noticeably slower than Postgres's, which is why start_period is longer here.
For MariaDB, the official image includes a dedicated healthcheck.sh script, which is the best option:
mariadb:
image: mariadb:11
environment:
MARIADB_ROOT_PASSWORD: rootsecret
MARIADB_DATABASE: appdb
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 5
start_period: 60s
--connect checks that a TCP connection works, and --innodb_initialized checks that the storage engine has finished initialising.
Redis
redis:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 3s
retries: 5
start_period: 5s
redis-cli ping prints PONG. If Redis is loading a large RDB or AOF file at startup, it replies with a LOADING error instead. Be aware that redis-cli can exit with 0 even when the server returns an error reply, so checking the actual output is safer:
healthcheck:
test: ["CMD-SHELL", "redis-cli ping | grep -q PONG"]
If Redis requires a password:
redis:
image: redis:7-alpine
command: ["redis-server", "--requirepass", "${REDIS_PASSWORD}"]
environment:
REDIS_PASSWORD: ${REDIS_PASSWORD}
healthcheck:
test: ["CMD-SHELL", "redis-cli --no-auth
👉🏻For More Check: Here