Run rails assets:precompile before loading application code on docker

Viewed 266

I am trying to create a rails app docker image that includes the asset pre-compilation step so speed up deployment.

I am new to docker and am aware that it is a best practice to copy the application code last (after installing application packages) as it will be the most frequently updated layer. Running the copy step earlier than package installation on will mean that packages will need to be reinstalled with every trivial changes in the application code.

My application is an API app with a front-end facing admin portal that requires front-end assets. We don't update these front-end assets as often as the actual rails code. So I was wondering if there was a way to do the asset precompilation step before the codebase copy step.

The following sequence works:

WORKDIR /soho

COPY Gemfile /soho/Gemfile
COPY Gemfile.lock /soho/Gemfile.lock
RUN bundle install

COPY package.json /soho/package.json
RUN npm install --global yarn
RUN npm install

COPY . /soho

RUN rake assets:precompile

However this means that precompile runs every time there is a code change not related to assets. I tried to put COPY step last like the following:

WORKDIR /soho

COPY Gemfile /soho/Gemfile
COPY Gemfile.lock /soho/Gemfile.lock
RUN bundle install

COPY package.json /soho/package.json
RUN npm install --global yarn
RUN npm install

COPY Rakefile /soho/Rakefile
COPY config /soho/config
RUN rake assets:precompile

COPY . /soho

This fails because the precompile step tries to initialize the rails app while the codebase is not yet present. I found that there used to be an option to set config.assets.initialize_on_precompile = false in application.rb but this option taken out since rails 4: https://github.com/rails/rails/commit/2d5a6de

Wondering if anyone has thought about this before, and whether this is something worth solving or do I just have to live with assets precompile running for every single deployment.

0 Answers
Related