Diagnosis
docker inspect my-app --format '{{.RestartCount}} {{.State.Health.Status}}'
docker logs --tail 50 my-app
The logs show the same connection error repeated across restarts. The restart policy is making things worse.
Fix
services:
api:
image: myorg/api:1.0.0
restart: on-failure
deploy:
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 5
window: 60s
For Compose v2 with deploy, the daemon respects the bounded
restart. For docker run, the equivalent is harder to enforce.
In the application, add retry-with-backoff:
import time
import requests
def fetch_with_retry(url, max_attempts=5):
for attempt in range(max_attempts):
try:
return requests.get(url, timeout=2)
except requests.exceptions.RequestException:
time.sleep(2 ** attempt + 0.1)
raise RuntimeError("dependency unreachable")