Use Redis for caching to a Docker Compose managed Rails project

Published: by Creative Commons Licence

Since Rails 5.2, Redis cache has been added to Rails for caching, in additional to the default memcache.

Add Redis to Gemfile

gem 'redis' # A Ruby client library for Redis

Build project

docker-compose build

Setup Redis for caching

  1. Update config/environments/production.rb.

    # Use Redis store for caching.
    config.cache_store = :redis_cache_store, { url: ENV.fetch("REDIS_URL_CACHING", "redis://localhost:6379/0") }
    
  2. Update config/environments/development.rb.

    Change memory_store to redis_cache_store and caching can be toggled by bundle exec rails dev:cache.

    config.cache_store = :redis_cache_store, { url: ENV.fetch("REDIS_URL_CACHING", "redis://localhost:6379/0") }
    
  3. Customize Redis URL

    Please refer to the previous blog post here.

Add Redis to docker-compose.yml

version: '3'

services:
  db:
    image: 'postgres:10-alpine'
    volumes:
      - 'postgres:/var/lib/postgresql/data'
    ports:
      - '5432:5432'

  redis:
    image: 'redis:5-alpine'
    command: redis-server
    ports:
      - '6379:6379'
    volumes:
      - 'redis:/data'

  web:
    depends_on:
      - 'db'
      - 'redis'
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    ports:
      - '3000:3000'
    volumes:
      - '.:/project'
    environment:
      - REDIS_URL_CACHING=redis://redis:6379/0

volumes:
  redis:
  postgres:

Start Server

docker-compose up --build