Adding a Redis Cache to a DevContainer Compose Stack
Your app needs a cache, and running Redis as a Compose service keeps the devcontainer close to production. This page adds Redis to the stack with a health check and shared networking, so the app reaches it at the hostname redis and the workspace waits until it's ready.
Prerequisites
You need a Compose-backed devcontainer.
- A
devcontainer.jsonusingdockerComposeFileand a workspaceservice. - A shared user-defined bridge network.
- The app's Redis connection settings.
Step-by-Step Implementation
- Declare the Redis service.
services:
redis:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
networks: [devnet]
networks: { devnet: {} }
- Gate the workspace on Redis health.
depends_on:
redis: { condition: service_healthy }
- Point the app at the hostname
redis.
REDIS_URL=redis://redis:6379
- Verify the app reaches it.
devcontainer exec --workspace-folder . -- redis-cli -h redis ping
Common Pitfalls
Redis issues are a startup race or a name that won't resolve.
| Symptom | Root Cause | Remediation |
|---|---|---|
| App can't reach redis | Not on the shared network | Put both services on the devnet bridge |
| App connects before Redis is ready | No health gate | Add healthcheck + service_healthy |
| Cache lost on rebuild (if persisted) | No volume for data | Mount a volume if you need persistence |
| Wrong host in the app | Hardcoded localhost | Use the service name redis |
Conclusion
Adding Redis is a small Compose service with a health check and shared networking: the app reaches it as redis, and the workspace waits until redis-cli ping succeeds. Ephemeral by default, it matches a cache's role; add a volume only if you need persistence.
FAQ
Should Redis data persist across rebuilds in dev? Usually not — a cache is ephemeral by nature, so the default in-memory service is fine and keeps rebuilds clean. If your workflow depends on warmed cache data, mount a volume at Redis's data directory, but for most dev use an ephemeral cache is correct.
Why can't my app reach redis?
The app and Redis must share a user-defined bridge network for name resolution. Put both on the same network and connect to the hostname redis (the service name), not localhost — inside the app container, localhost is the app, not Redis.
How do I make the app wait for Redis?
Add a healthcheck using redis-cli ping and set the workspace's depends_on to condition: service_healthy, so the app starts only once Redis is accepting connections rather than racing its startup.
Related
- Up to Docker Compose Integration for Multi-Service Apps — the Compose model.
- Configuring a Postgres Service in a DevContainer Compose Stack — a persistent backing service.
- Resolving DNS Failures in Compose Networks — when the name won't resolve.