brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: make depends_on wait for a healthy database, not just a started one

Docker
~/tips/tip-docker-depends-on-healthy

services:

Makes a container wait until its dependency passes its healthcheck before it starts.

By default depends_on only waits until the other container has started. A database that is still initialising counts as started, and your app crashes on its first query.

The fix is a healthcheck on the dependency and a long-form depends_on with a condition.

services:
  db:
    image: postgres:17
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10
  app:
    image: myapp
    depends_on:
      db:
        condition: service_healthy

Now Compose holds app back until db reports healthy. There is also service_completed_successfully, which waits for a container to exit with code 0. That one suits a migration job that has to finish before the app starts.

The healthcheck is worth having anyway. docker ps then shows the status as healthy or unhealthy next to the uptime, and that is more honest than a container that merely runs. Keep the interval short while you are testing, and a bit longer in real use.

The caveat: this only orders the startup. If the database dies later, your app is not stopped for it, so it still needs to cope with a lost connection. Also pick a health command that exists inside the image. pg_isready ships with the Postgres image, but a minimal image may not have curl.

Further reading: Compose services reference: depends_on and healthcheck, On this site: docker inspect tells you if a container is healthy, not just running, On this site: ${VAR:?message} makes Compose stop when a variable is missing, On this site: Guide: make Docker Compose wait until the database is really ready, not just started

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link