If you recreate a database container, an app that keeps its connection open can end up talking to a dead one. Compose can restart the app for you when the dependency is updated.
It is a field of the long depends_on syntax:
services:
api:
image: my-api:latest
depends_on:
postgres:
condition: service_healthy
restart: true
postgres:
image: postgres:17
With restart: true, Compose restarts api after it updates postgres. The docs mention Compose 2.17.0 as the version that introduced it, so run docker compose version if the key is rejected. The service_healthy condition is the other half: it keeps the app from starting before the database accepts connections.
Caveat: it only reacts to a restart that a Compose operation controls, such as docker compose up -d recreating the dependency. If the engine restarts the database after a crash, or you run docker restart by hand, the app is left alone, so keep a reconnect loop in the app for that case.
Without the key, the usual fix is to restart the app yourself after the update with docker compose restart api.
Further reading: Compose workload spec: depends_on