DEV Community

Cover image for Why docker compose up Leaves Your API Connected to a Dead Database
hoagminh
hoagminh

Posted on Edited on

Why docker compose up Leaves Your API Connected to a Dead Database

Suppose you raise the memory limit on your postgresql service (or tweak one environment variable on Redis) and redeploy:

docker compose up -d
Enter fullscreen mode Exit fullscreen mode

Docker Compose detects that postgresql changed and recreates its container. Every other service—api, worker, scheduler—was untouched, so Compose prints Running next to them and exits 0.

Then the first real request hits api and fails with ECONNRESET, connection terminated unexpectedly, or a stale container IP cached in a connection pool.

Unless the upstream Compose file explicitly sets depends_on.<service>.restart: true, docker compose up recreates a changed dependency while leaving its running dependents attached to the old dead container.

The lazy workaround is docker compose restart on the whole stack—which unnecessarily bounces unrelated services (like object storage, analytics, or a separate cache) and causes avoidable downtime.

This is the bug (BUG-023) behind targeted dependent restarts in Nitrobase (services/apps/dependents.ts and features/apps/app-jobs.server.ts).

Nitrobase has only recently launched and is still in Beta. This mechanism is not a service mesh or connection-draining proxy; its job is practical and surgical: figure out exactly which containers compose up recreated, walk depends_on transitively, and restart only the running dependents that still point at the old container—in dependency order.

1. Fingerprint containers before and after compose up

Instead of guessing from YAML diffs what Compose might recreate, Nitrobase reads the ground truth directly from Docker right before and right after docker compose up (composeIdentityCommand):

docker inspect --format '{{index .Config.Labels "com.docker.compose.service"}}\t{{.Id}}\t{{.State.StartedAt}}\t{{.State.Status}}'
Enter fullscreen mode Exit fullscreen mode

Each service's identity is fingerprinted as a sorted list of <id>@<startedAt> across its containers (parseContainerIdentities):

  • Same fingerprint before & after up: Compose left this service running untouched.
  • Different fingerprint: Compose recreated or (re)started this service.
  • Nothing before up (first deploy): Nothing was running beforehand, so nothing needs a follow-up restart.

Because this compares actual container IDs and start timestamps, it automatically handles edge cases where Compose already restarted a dependent via depends_on.restart: true—that dependent's fingerprint changed too, so Nitrobase will not restart it a second time.

2. Walk depends_on transitively—but skip one-shot jobs

Not every depends_on edge represents a live network connection:

services:
  migrate:
    command: ["prisma", "migrate", "deploy"]
    restart: "no"
  api:
    depends_on:
      postgresql:
        condition: service_healthy
      migrate:
        condition: service_completed_successfully
  worker:
    depends_on:
      - api
Enter fullscreen mode Exit fullscreen mode

If postgresql is recreated, both api (direct dependent) and worker (transitive dependent through api) need to reconnect.

On the other hand, docker compose up re-runs the one-shot migrate container on every deploy—its fingerprint always changes, even though api holds zero live connections to a finished migration container.

dependentsToRestart handles both cases cleanly:

Edge / service type Included in restart graph? Why
depends_on: [postgresql] or condition: service_healthy / service_started Yes (walked transitively, cycle-safe) Dependent services hold live pools or cached DNS IPs to the recreated service
condition: service_completed_successfully (runtimeOnly: true) No One-shot init/migration step; dependents do not hold runtime connections to it
oneShot services (containers that run once and exit) No (never a restart cause) Re-running a migration on deploy must not bounce healthy long-running services
Unchanged unrelated services (e.g. minio, redis) No Not reachable from any changed service in depends_on; zero unnecessary downtime
Already recreated/restarted services No Already reconnected to their dependencies during compose up

The final restart list is topologically sorted dependencies-first (orderByDependencies), matching how docker compose restart <services...> brings them back up.

3. Wait until the new DB is healthy before restarting dependents

Timing matters just as much as which services you pick (restartDependents in app-jobs.server.ts):

1. Snapshot container identities (`before`)
        v
2. Run `docker compose up -d`
        v
3. Wait until the app is healthy (`waitUntilHealthy` #1)
        └─ Ensures recreated `postgresql` is actually accepting connections first!
        v
4. Snapshot container identities (`after`) -> `dependentsToRestart(before, after, dependsOn)`
        v
5. Restart ONLY the affected running dependents (`composeRestartServicesCommand`)
        v
6. Run a fresh `waitUntilHealthy` #2 (its own full timeout budget)
Enter fullscreen mode Exit fullscreen mode

Two details here prevent subtle deploy flakes:

  • Restarting after the first readiness pass ensures api and worker do not immediately crash-loop trying to connect while the recreated database is still running recovery.
  • Giving the second waitUntilHealthy its own timeout budget ensures a slow database restart does not eat up the time budget needed for the restarted API containers to boot cleanly.
  • Opt-out for self-healing stacks: Templates whose services already reconnect cleanly without a restart can disable this step with restart_dependents = false.

What depends_on analysis still cannot see

This approach relies on the depends_on graph declared in the Compose file. If an app connects to postgresql or redis without declaring it in depends_on—for example, a custom Compose file that relies purely on retry loops—Nitrobase will not know that service depends on the recreated container. Similarly, external apps connected across separate Compose projects via shared database links are outside a single project's depends_on graph.

My checklist for updating dependencies in Docker Compose

  • Remember that docker compose up -d does not restart dependents of a recreated service unless depends_on.<svc>.restart: true is configured
  • Fingerprint containers (Id + StartedAt) before and after up instead of guessing what Compose recreated
  • Walk depends_on transitively, but exclude one-shot containers and condition: service_completed_successfully edges
  • Wait until recreated databases pass health checks before restarting their dependents
  • Re-verify readiness with a fresh timeout budget after restarting dependents

Blindly restarting the entire stack trades one problem for unnecessary downtime. Comparing container identities around compose up lets you bounce only the services that actually lost their upstream—and leave everything else running.

Nitrobase source code: https://github.com/AydenGroup/nitrobase

Top comments (0)