Docker has become a popular tool in recent years for building and deploying applications in a portable and scalable way. However, the build process can sometimes be slow, especially for large applications with many dependencies. In this article, we’ll explore how we can optimize our Dockerfile to speed it up.

When building a rails app for production we would need to do the following steps in the docker file

1
2
3
4
COPY . .
bundle install
yarn install
bundle exec rails assets:precompile

Docker after building each step it will cache that step. If the instructions/context of that steps or steps before haven’t change then docker will use the cache.

So we need to make docker understand that there is no change, hence we can use the cache instead of rebuilding it.

To keep it simple:

Don’t do:

1
2
3
COPY . .
RUN bundle install
RUN yarn install

do

1
2
3
4
5
6
7
8
9
COPY ./Gemfile .
COPY ./Gemfile.lock .
RUN bundle install

COPY ./package.json .
COPY ./yarn.lock .
RUN yarn install

COPY . .

Now docker would now use cache seeing that there is no change in the Gemfile, Gemfile.lock, etc. Before docker would have ran bundle and yarn because of any change in any file, will change the hash resulting in rebuilding the remaining steps.

Reference: https://docs.docker.com/build/cache/