Subscribe

Stop your app racing the database: depends_on with healthchecks

Plain depends_on only waits for a container to start, not for Postgres to accept connections. Here is how I fixed the race in a Go app's compose file with healthchecks, service_healthy and service_completed_successfully, plus a pg_isready trap I hit on the way.

Stop your app racing the database: depends_on with healthchecks

You write a compose file with Postgres and your app, add depends_on: [postgres], run docker compose up and the app dies with "connection refused". You run it again and it works. So you move on, and a week later it fails again on a fresh laptop or in CI.

That's a race, and plain depends_on doesn't stop it. In this blog we will look at why, and fix it properly with healthchecks and depends_on conditions. I'll use shorty, the small URL shortener in Go with Postgres and Redis that I'm building in this series (the design is in Designing a URL shortener from requirements to scale). Level is beginner. You need Docker with Compose and you should know what a service in a compose file is.

I used Docker 29.8.2, Compose v5.5.0, Postgres 18.7 (postgres:18-alpine) and Redis 8.10 (redis:8-alpine).

What shorty needs at startup

shorty has three moving parts that care about order:

  1. migrate: a one-shot container that runs /shorty migrate up and exits.
  2. api: the HTTP server. It pings Postgres when it starts and exits if the ping fails.
  3. Postgres and Redis, which the other two talk to.

The api and the migration use the same image. The binary has the migrations embedded, as shown in Talking to Postgres from Go with pgx and sqlc, so command: just picks what it does.

The naive version

This is what most of us write first. I wrote it on purpose to see it break.

name: shorty

x-db-env: &db-env
  DATABASE_URL: postgres://shorty:shorty@postgres:5432/shorty?sslmode=disable

services:
  postgres:
    image: postgres:18-alpine
    environment:
      POSTGRES_USER: shorty
      POSTGRES_PASSWORD: shorty
      POSTGRES_DB: shorty
    volumes:
      - pgdata:/var/lib/postgresql

  redis:
    image: redis:8-alpine

  migrate:
    build: .
    image: ${SHORTY_IMAGE:-shorty:dev}
    command: ["/shorty", "migrate", "up"]
    environment:
      <<: *db-env
    depends_on:
      - postgres

  api:
    build: .
    image: ${SHORTY_IMAGE:-shorty:dev}
    environment:
      <<: *db-env
      REDIS_URL: redis://redis:6379/0
    ports:
      - "127.0.0.1:${API_PORT:-8080}:8080"
    depends_on:
      - postgres
      - redis
      - migrate

volumes:
  pgdata:

The image name comes from a variable because I share this Docker with other projects and didn't want to clobber someone else's shorty:dev. If you don't care, it's just shorty:dev.

With an empty volume:

docker compose -f compose.naive.yaml up -d
docker compose -f compose.naive.yaml ps -a --format 'table {{.Service}}\t{{.Status}}'
SERVICE    STATUS
api        Exited (1) 6 seconds ago
migrate    Exited (1) 6 seconds ago
postgres   Up 7 seconds
redis      Up 7 seconds

Both of them died within a second itself.

migrate-1  | shorty: failed to initialize: failed to connect to `user=shorty database=shorty`: 192.168.107.2:5432 (postgres): dial error: dial tcp 192.168.107.2:5432: connect: connection refused
api-1      | shorty: postgres ping: failed to connect to `user=shorty database=shorty`: 192.168.107.2:5432 (postgres): dial error: dial tcp 192.168.107.2:5432: connect: connection refused

And docker compose up -d returned exit code 0. Compose did its job, it started every container in the right order. It just has no idea that "started" and "ready" are different things.

Then I ran exact same up -d again. Migration ran, api came up, /readyz said ok. The volume was already initialised the second time, so Postgres was up in a fraction of a second and won the race. This is why the bug hides so well. It only shows up on the first boot, which is a new laptop, a new CI runner, or you after down -v.

Why Postgres says ready twice

The Postgres logs explain the first failure. On the first boot the official image runs initdb, then starts a temporary server to create your user and database and run any init scripts, stops it, and only then starts the real one.

waiting for server to start....2026-11-19 07:30:37.408 UTC [45] LOG:  starting PostgreSQL 18.7 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
2026-11-19 07:30:37.410 UTC [45] LOG:  listening on Unix socket "/run/postgresql/.s.PGSQL.5432"
2026-11-19 07:30:37.439 UTC [45] LOG:  database system is ready to accept connections
PostgreSQL init process complete; ready for start up.
2026-11-19 07:30:38.946 UTC [1] LOG:  starting PostgreSQL 18.7 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
2026-11-19 07:30:38.946 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
2026-11-19 07:30:38.946 UTC [1] LOG:  listening on IPv6 address "::", port 5432
2026-11-19 07:30:38.953 UTC [1] LOG:  database system is ready to accept connections

Look at the first block. The temporary server listens only on the Unix socket inside the container. No TCP. So for about a second and a half, other containers get "connection refused" even though the logs already say "ready to accept connections". Keep that in mind, it comes back in a minute.

Healthchecks and conditions

The fix has two halves. Each service that others wait on gets a healthcheck, and the services that wait use the long form of depends_on with a condition.

  postgres:
    image: postgres:18-alpine
    environment:
      POSTGRES_USER: shorty
      POSTGRES_PASSWORD: shorty
      POSTGRES_DB: shorty
    ports:
      - "127.0.0.1:${PG_PORT:-5432}:5432"
    volumes:
      - pgdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U shorty -d shorty"]
      interval: 2s
      timeout: 3s
      retries: 15

  redis:
    image: redis:8-alpine
    command: ["redis-server", "--save", "", "--appendonly", "no", "--maxmemory", "64mb", "--maxmemory-policy", "allkeys-lru"]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 2s
      timeout: 3s
      retries: 15

pg_isready ships in the Postgres image and exits 0 when the server accepts connections. redis-cli ping does the same job for Redis. With interval: 2s and retries: 15, Compose gives each one about 30 seconds before it marks it unhealthy.

Note the -h 127.0.0.1 on pg_isready. I didn't have it at first, and that's the next section.

There are three conditions you can wait for:

  • service_started: the default, same as the short form. Container is running, nothing more.
  • service_healthy: the healthcheck has passed.
  • service_completed_successfully: the container ran and exited with code 0. Made for one-shot jobs like migrations.

So the migration waits for a healthy Postgres, and the api waits for the migration to finish:

  migrate:
    build: .
    image: ${SHORTY_IMAGE:-shorty:dev}
    command: ["/shorty", "migrate", "up"]
    environment:
      <<: *db-env
    depends_on:
      postgres:
        condition: service_healthy
    restart: "no"

  api:
    build: .
    image: ${SHORTY_IMAGE:-shorty:dev}
    environment:
      <<: *db-env
      REDIS_URL: redis://redis:6379/0
    ports:
      - "127.0.0.1:${API_PORT:-8080}:8080"
    depends_on:
      migrate:
        condition: service_completed_successfully
      redis:
        condition: service_healthy
    restart: unless-stopped

The api doesn't list Postgres at all. It doesn't need to. The migration can only have exited 0 if Postgres was healthy, so waiting for migrate covers it. One less line to keep in sync.

I also have a seed service that loads a few test links with psql after migrate, with the same service_completed_successfully condition. The api doesn't wait for it.

The pg_isready trap

My first healthy version had pg_isready -U shorty -d shorty, no host. It worked every time on a fresh volume, so I was quite sure about it. Then I wondered what happens when the first boot is slow, say an init script that loads a big schema. I added a test override that mounts a script into /docker-entrypoint-initdb.d which just sleeps 8 seconds:

#!/bin/sh
# Pretend the first-boot init is slow (a big schema or data load).
echo "slow init script: sleeping 8s"
sleep 8
# compose.slowinit.yaml
services:
  postgres:
    volumes:
      - ./initdb:/docker-entrypoint-initdb.d:ro
docker compose -f compose.yaml -f compose.slowinit.yaml up -d
 Container shorty-redis-1 Healthy
 Container shorty-migrate-1 Error service "migrate" didn't complete successfully: exit 1
service "migrate" didn't complete successfully: exit 1

And ps showed this, which honestly confused me for a minute:

SERVICE    STATUS
api        Created
migrate    Exited (1) Less than a second ago
postgres   Up 5 seconds (healthy)
redis      Up 5 seconds (healthy)
seed       Created

Postgres healthy, migration got connection refused. Without -h, pg_isready talks to the Unix socket, and the temporary init server listens on exactly that socket. So the healthcheck passed during init, while the init script was still sleeping and nothing was on TCP port 5432. Other containers can only reach Postgres over TCP (the network side of that is in Docker networking explained).

Adding -h 127.0.0.1 makes the check go over TCP, the same way the app connects. Same slow init, again from an empty volume:

SERVICE    STATUS
api        Up Less than a second (health: starting)
migrate    Exited (0) Less than a second ago
postgres   Up 11 seconds (healthy)
redis      Up 11 seconds (healthy)
seed       Up Less than a second

up -d took 11.7 seconds and the migration ran in first try. Notice the good part of the failed run too: up exited 1 and the api stayed in Created. That is what you want. A clear failure beats an api that boots against a database with no tables.

Waiting for the api with --wait

depends_on only orders containers inside Compose. Your own scripts, for example a test step or a curl right after up, need the same thing. That's --wait:

docker compose up -d --wait
echo "exit $?"
 Container shorty-migrate-1 Exited
container shorty-seed-1 exited (0)
exit 1

Exit 1, and the api was fine. The first time I ran this I had piped the output into tail, so $? was the exit code of tail and I happily believed it was 0. Only when I ran it again without the pipe I saw the 1.

The reason is the seed. --wait is fine with a one-shot container that exits, as long as another service waits for it with service_completed_successfully. That's why migrate doesn't trip it. Nothing depends on seed, so when it exits --wait treats it as a service that stopped and gives up, even with exit code 0.

The fix is to tell --wait what you actually care about:

docker compose up -d --wait api
echo "exit $?"
 Container shorty-api-1 Healthy
exit 0

Naming the api starts it plus everything it depends on, and waits until it is healthy. The seed doesn't start this way, since the api doesn't depend on it. Run docker compose up -d seed afterwards if you want the test links. The api counts as healthy because shorty's image has a HEALTHCHECK that runs /shorty healthcheck. I'll lean on --wait a lot when we run integration tests in CI later in the series.

After startup, you are on your own

This is the part people miss. Basically, depends_on is about startup order only. When Postgres goes away later, Compose does nothing to the api by default. I stopped Postgres with the stack running:

docker compose stop postgres
curl -s -w ' %{http_code}\n' localhost:8080/readyz
curl -s -w ' %{http_code}\n' localhost:8080/golang
{"postgres":"down: FATAL: terminating connection due to administrator command (SQLSTATE 57P01)","redis":"ok"}
 503
<a href="https://go.dev/doc/">Found</a>.

 302

/readyz went to 503, as it should. The redirect still worked, because that link was in Redis. After docker compose start postgres, readyz went back to 200 a couple of seconds later on its own. pgxpool throws away broken connections and makes new ones, so the app didn't need a restart. Your app has to handle that itself. No compose setting does it for you.

If your app can't reconnect, there is restart: true on a dependency:

  api:
    depends_on:
      postgres:
        condition: service_healthy
        restart: true

With that, docker compose restart postgres also restarts the api once Postgres is healthy again. I tried it and the output showed Container shorty-api-1 Restarting right after postgres-1 Healthy. It only kicks in for restarts Compose itself does, not when Postgres crashes on its own. I didn't keep it for shorty, it doesn't need it as such.

Same idea with MySQL

My blog runs Ghost and MySQL 8.4 on Compose, and it uses the same pattern. MySQL takes much longer on first boot on a small instance, so it has a start_period, where failed checks don't count yet:

    healthcheck:
      test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p\"$$MYSQL_ROOT_PASSWORD\" --silent"]
      interval: 5s
      timeout: 5s
      retries: 30
      start_period: 30s

-h 127.0.0.1 again, for the same reason. The MySQL image also runs a temporary server during init. There is more about that box in Running Ghost 6 and MySQL 8 on a 2 GB t3.small.

Cleaning up

docker compose down -v

-v removes the pgdata volume, so the next up is a first boot again. That's actually the best way to test any of this. If your stack only works on the second up, you have a race.