DEV Community

K-Sato
K-Sato

Posted on

 

Cache Rails gems using docker-compose

Introduction

Let's suppose you have a docker-compose.yml like the one below.
You have to run docker-compose build every time you add/remove a gem to/from your Gemfile and it is very time-consuming.
It would be great if I could just run bundle install and get back to developing the application.
Well... I'll show you exactly that in this post.

version: "3"
services:
  app:
    build: .
    volumes:
      - .:/app
    depends_on:
      - postgres
  postgres:
    image: postgres
    ports:
      - "5432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  postgres-data:

Set up your docker-compose.yml

Follow the steps below.

  • (1) Set up BUNDLE_PATH using environment.
  • (2) Set up the named volume bundle_path and add it to the top level volumes.

Here is the modified docker-compose.yml.

version: "3"
services:
  app:
    build: .
    volumes:
      - .:/app
      - bundle_path:/bundle # New
    environment:
      - BUNDLE_PATH=/bundle/vendor #New
    depends_on:
      - postgres
  postgres:
    image: postgres
    ports:
      - "5432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data

volumes:
  bundle_path: # New
  postgres-data:

How to use it?

Create the cache of the gems

Run the command below to create the cache of the gems after you modified your docker-compose.yml.

$ docker-compose app bundle install

Add or Remove a gem

  • (1) Stop the running containers.
$ docker-compose down
  • (2) Add a new gem and run the command below.
$ docker-compose run app bundle install
  • (3) Get the containers running again.
$ docker-compose up

Top comments (2)

Collapse
 
gathuku profile image
Moses Gathuku • Edited

There must be a typo on first command .

docker-compose app bundle install

Enter fullscreen mode Exit fullscreen mode

Maybe you meant

docker-compose run app bundle install
Enter fullscreen mode Exit fullscreen mode

Thanks for the good work.

Collapse
 
thomasbromehead profile image
thomasbromehead

Very helpful thanks, remember to chmod that directory if you are running the container as a non-root user!

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git