Docker Compose in Practice: Dependencies, Healthchecks, and Environment Configuration
Docker Compose healthcheck guide: pair depends_on with service_healthy, run migrations once, and handle env files and variable precedence.
healthcheck to databases and other dependencies, use depends_on with condition: service_healthy, and run migrations as a one-off service with condition: service_completed_successfully. Then make configuration predictable: understand which source wins when the same variable is set in several places, use ${VAR:?message} for required values, keep secrets in Compose secrets rather than plain environment variables, and remove duplication with extension fields.
The API container starts, tries to connect to Postgres, and crashes with “connection refused”. Postgres started first, as depends_on promised, but it was still initializing its data directory. On a fast laptop it works most of the time; in CI it fails one run in five. Someone adds sleep 10 to the API’s start command, and the flakiness moves somewhere else.
The Compose fundamentals article showed the short form of depends_on, which only waits for a container to be started. Compose also supports a long form that waits for a dependency to be healthy, as reported by a healthcheck: a command Docker runs inside the container at intervals, where exit code 0 means healthy.
Healthchecks and real startup order
services:
db:
image: postgres:15
environment:
POSTGRES_USER: billing
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
POSTGRES_DB: billing
secrets: [db_password]
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U billing -d billing"]
interval: 5s
timeout: 3s
retries: 10
start_period: 10s
cache:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
migrate:
image: ghcr.io/acme/billing-api:${API_TAG:-dev}
command: ["node", "dist/migrate.js"]
environment: &api-env
DATABASE_URL: postgres://billing@db:5432/billing
REDIS_URL: redis://cache:6379
DATABASE_PASSWORD_FILE: /run/secrets/db_password
secrets: [db_password]
depends_on:
db:
condition: service_healthy
api:
image: ghcr.io/acme/billing-api:${API_TAG:-dev}
build: .
environment: *api-env
secrets: [db_password]
ports:
- "127.0.0.1:8080:8080"
depends_on:
migrate:
condition: service_completed_successfully
cache:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:8080/healthz"]
interval: 10s
timeout: 3s
retries: 3
restart: unless-stopped
secrets:
db_password:
file: ./secrets/db_password.txt
volumes:
pgdata:
Now the startup sequence is explicit and reliable: Postgres starts and reports healthy once pg_isready succeeds; the migration service runs against the ready database and exits; the API starts only after the migration finished with exit code 0 and Redis answers PONG.
| Condition | Waits until | Use for |
|---|---|---|
service_started |
The dependency’s container has started (the short form’s behavior) | Services that retry connections themselves |
service_healthy |
The dependency’s healthcheck passes | Databases, caches, brokers, internal APIs |
service_completed_successfully |
The dependency ran to completion with exit code 0 | Migrations, seeders, one-time setup jobs |
Healthcheck settings that matter
test:["CMD", ...]runs a command directly;["CMD-SHELL", "..."]runs it through/bin/sh. The command must exist in the image, so distroless images need a small built-in health binary or a health subcommand of your application.interval,timeout,retries: check every interval, fail a check that takes longer than the timeout, and mark unhealthy after that many consecutive failures.start_period: a grace period during which failures do not count, for services with slow startup such as JVM applications or databases replaying a write-ahead log.
One common misunderstanding: plain Docker and Compose do not restart a container just because it became unhealthy. The status is reported in docker compose ps and used for depends_on, but the restart policy only acts when the main process exits. Orchestrators such as Kubernetes do restart on failed liveness probes; on a single host, make the application exit when it is truly broken.
Even with healthchecks, write applications that retry connections with backoff. Dependencies can restart after startup too, and a service that crashes on the first failed connection will still be fragile.
Environment configuration without surprises
Which value wins
The same variable can come from several places. For a container’s environment, Compose applies this precedence, highest first:
docker compose run -e NAME=valueon the command line.- The
environmentkey in the Compose file, including values interpolated from your shell or.env. - The
env_filekey. ENVinstructions in the image’s Dockerfile.
When a value is not what you expect, docker compose config shows the resolved file, and docker compose exec api env shows what the process actually received.
Interpolation, defaults and required values
image: ghcr.io/acme/billing-api:${API_TAG:-dev} # default if unset or empty
environment:
STRIPE_API_KEY: ${STRIPE_API_KEY:?set STRIPE_API_KEY in .env} # fail fast if missing
FEATURE_FLAGS: ${FEATURE_FLAGS-} # empty string if unset
Compose fills these from your shell environment and from a .env file next to the Compose file. The :? form stops docker compose up with your message when a required value is missing, which is far better than an API that starts and fails on its first payment request. Commit a .env.example with every variable documented, and keep the real .env out of version control.
Secrets
Environment variables are easy to leak: they show up in docker inspect, in crash reports and in debug endpoints that print the environment. Compose secrets mount a file into the container at /run/secrets/<name> instead. Many official images, including Postgres, MySQL and MariaDB, accept *_FILE variants of their password variables for exactly this, as in the example above. On a single host the secret is a local file, so this is about reducing accidental exposure rather than strong encryption; Docker secrets goes further.
Keeping files DRY
Top-level keys starting with x- are ignored by Compose, which makes them a place to define reusable YAML anchors:
x-api-common: &api-common
image: ghcr.io/acme/billing-api:${API_TAG:-dev}
environment:
DATABASE_URL: postgres://billing@db:5432/billing
REDIS_URL: redis://cache:6379
restart: unless-stopped
services:
api:
<<: *api-common
ports: ["127.0.0.1:8080:8080"]
worker:
<<: *api-common
command: ["node", "dist/worker.js"]
The API and the background worker share an image and configuration and differ only in command and ports. For differences between environments, layer files: compose.yaml for the shared definition, compose.override.yaml for local development, and compose.ci.yaml or compose.prod.yaml passed with -f where needed.
A few more practical settings
- Resource limits:
deploy.resources.limitswithcpusandmemoryis honored by Compose V2 on a single host, and keeps a runaway service from starving the others. - Logging: set
logging.options.max-sizeandmax-fileso the default JSON log files do not fill the disk on long-running hosts. - Init:
init: trueruns a tiny init process as PID 1, which forwards signals and reaps zombie processes for applications that do not. - File watching: recent Compose releases include an experimental
docker compose watchthat syncs or rebuilds services when files change, an alternative to bind-mounting source code. It is worth trying, but still evolving.
Frequently Asked Questions
Does depends_on wait for the database to be ready?
Only in its long form with condition: service_healthy and a healthcheck on the database. The short form waits only until the container starts, which is often before the database accepts connections.
How do I run database migrations before starting my app in Compose?
Define the migration as its own service that depends on the database being healthy, then make the app depend on the migration service with condition: service_completed_successfully. The app starts only after migrations exit with code 0.
Does Docker restart unhealthy containers?
No. Docker and Compose report health status and use it for depends_on, but restart policies only act when the main process exits. Kubernetes liveness probes do restart containers; on a single host, make the application exit when it cannot recover.
What is the difference between .env and env_file in Docker Compose?
The .env file next to the Compose file provides values for ${VARIABLE} substitution inside the Compose file itself. env_file loads variables from a file into a service’s container environment.
Explicit readiness, predictable configuration
Healthchecks turn “it usually starts” into “it always starts”, one-off services make migrations part of the startup graph, and clear rules for variables and secrets make every environment reproducible. With those in place, the same Compose project runs on a laptop, in CI and on a small server with the same behavior, which is exactly the point of using it. For the full reference, see the Compose healthcheck reference and the Compose startup order guide. Related reading on this site: logs and resource limits.
Originally posted on 12 July 2023 and post last modified on 4 December 2026