'Is there a way to speed up the dependency downloading and installation when building a Linux image with Ruby on Rails?

I’m using Docker 20.10.12. I have a Dockerfile based on an Ubuntu image, in which I want to run a Ruby on Rails application. The image is part of a docker-compose piece

 myapp:
    restart: "no"
    build: ../app
    ports:
      - "3000:3000"
    expose:
      - '3000'
    environment:
    …

When I rebuild, and then bring things back up, it takes quite a while to rebuild the image. Specifically the parts where I install the dependencies …

# install basic dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
  build-essential \
  bzip2 \
  ca-certificates \
  git \
  gnupg \
  curl \
  autoconf \
  bison \
  build-essential \
  libcurl4-openssl-dev \
  libyaml-dev \
  libreadline6-dev \
  zlib1g-dev \
  libncurses5-dev \
  libffi-dev \
  # update libgdbm3 to libgdbm5 when we move to higher ubuntu version
  libgdbm3 \
  libgdbm-dev \
  libxml2-dev \
  mysql-client \
    …
  libmysqlclient-dev \
  libsqlite3-dev \
  libpq-dev \
  libmemcached-dev \
  apt-utils \
  socat \
  && rm -rf /var/lib/apt/lists/*

And then install the Ruby environment and the application dependencies …

# installl rbenv
RUN git clone https://github.com/rbenv/rbenv.git /usr/local/rbenv \
&&  git clone https://github.com/rbenv/ruby-build.git /usr/local/rbenv/plugins/ruby-build \
&&  git clone https://github.com/jf/rbenv-gemset.git /usr/local/rbenv/plugins/rbenv-gemset \
&&  /usr/local/rbenv/plugins/ruby-build/install.sh
ENV PATH /usr/local/rbenv/bin:$PATH
ENV RBENV_ROOT /usr/local/rbenv

RUN echo 'export RBENV_ROOT=/usr/local/rbenv' >> /etc/profile.d/rbenv.sh \
&&  echo 'export PATH=/usr/local/rbenv/bin:$PATH' >> /etc/profile.d/rbenv.sh \
&&  echo 'eval "$(rbenv init -)"' >> /etc/profile.d/rbenv.sh

RUN echo 'export RBENV_ROOT=/usr/local/rbenv' >> /root/.bashrc \
&&  echo 'export PATH=/usr/local/rbenv/bin:$PATH' >> /root/.bashrc \
&&  echo 'eval "$(rbenv init -)"' >> /root/.bashrc

ENV CONFIGURE_OPTS --disable-install-doc
ENV PATH /usr/local/rbenv/bin:/usr/local/rbenv/shims:$PATH

…
# Install Rails
RUN cd $APP_HOME
RUN RBENV_VERSION=$(eval ${RBENV_VERSION}); bin/bundle install

These sections don’t typically change a whole lot from rebuilding the various images, and I was curious if there’s a way to cache this data or do something else to speed up my builds when I rebuild the image.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source