b. Docker Compose
Add the redis service to compose.yaml and expose the Redis hostname to each microservice through environment variables.
Add Redis
redis:
image: redis:7-alpine
hostname: redis
ports:
- 6379:6379
volumes:
- redis_data:/data
command: redis-server --appendonly yes
The --appendonly yes flag enables the AOF persistence mode: every write is logged to disk, so cached data survives a Redis container restart.
Add the named volume at the bottom of compose.yaml:
Connect microservices to Redis
Each microservice that uses the cache must know where Redis is running. Pass the connection details as environment variables:
account:
build:
context: ./account-service
dockerfile: Dockerfile
hostname: account
environment:
DATABASE_HOST: db
DATABASE_PORT: 5432
DATABASE_DB: ${DB_NAME:-store}
DATABASE_USERNAME: ${DB_USER:-store}
DATABASE_PASSWORD: ${DB_PASSWORD:-devpass}
REDIS_HOST: redis
REDIS_PORT: 6379
deploy:
replicas: 2
depends_on:
- db
- redis
Apply the same REDIS_HOST and REDIS_PORT variables to any other service that reads or writes the cache (e.g. auth).
Full compose.yaml
Redis port exposure
Port 6379 is published to the host for development convenience — it allows direct inspection with redis-cli from your machine. In production, remove this ports mapping so Redis is only reachable from within the Docker network.