Docker Compose Redis Healthcheck - Guarantee Startup Order
Problem
depends_on alone only guarantees the Redis container has “started”, not that it’s “ready”. If the app connects while Redis is still initializing, you get Connection refused errors.
Solution
services:
app:
build: .
depends_on:
redis:
condition: service_healthy # start only when healthy
environment:
- REDIS_URL=redis://redis:6379
redis:
image: redis/redis-stack:latest
environment:
- REDIS_ARGS=--maxmemory 512mb --maxmemory-policy allkeys-lru
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
volumes:
- redis-data:/data
deploy:
resources:
limits:
memory: 768M
volumes:
redis-data:
Key Points
redis-cli pingreturningPONGsignals healthy status.start_period: 30sgives Redis 30 seconds to initialize without being marked unhealthy.--maxmemory-policy allkeys-lruauto-evicts the oldest keys when memory is full. The safest default for cache use cases.deploy.resources.limits.memoryprevents Redis from consuming all host memory. Set container-level limits independently of Redis’smaxmemory.