Skip to content

Instantly share code, notes, and snippets.

@huacnlee
Last active September 8, 2020 05:15
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save huacnlee/cd47d5550c47bc1cc46b91e679f014da to your computer and use it in GitHub Desktop.
Save huacnlee/cd47d5550c47bc1cc46b91e679f014da to your computer and use it in GitHub Desktop.
给 Rails 应用 Docker Image 打包过程增加 cache,依靠 GitLab CI 的 cache 来加速

.yarnrc

我们需要在 Rails 项目根目录配置 .yarnrc 告诉 Yarn 我们需要将 npm 的包缓存到 vendor/cache/npm 目录。

registry "https://registry.npm.taobao.org"
lastUpdateCheck 1561690751463
yarn-offline-mirror "./vendor/cache/npm"     
yarn-offline-mirror-pruning true

.gitlab-ci.yml

我们配置 GitLab CI,并开启对 vendor/cache 等目录的缓存,同时确保 bundle install 之后执行 bundle cache 让 Bundler 把 RubyGems 的 cache 放入 vendor/cache 里面。

cache:
  key: ${CI_JOB_NAME}
  paths:
    - vendor
    - node_modules
    
test:
  stage: test
  script:
    - yarn config set registry https://registry.npm.taobao.org/
    - bundle config mirror.https://rubygems.org https://gems.ruby-china.com
    - bundle install --quiet --jobs $(nproc)
    - bundle cache
    - rails db:create db:migrate
    - rails test

build:
  stage: build
  script:
    - docker build . -t foo:latest

Dockerfile

因为前面有了 vendor/cache 的缓存,现在 Docker Build 也能利用它们了。

FROM ruby:2.6.3

WORKDIR /home/app

ADD Gemfile Gemfile.lock package.json yarn.lock .yarnrc ./
ADD vendor/cache vendor/cache
RUN bundle install --deployment --jobs 20 --retry 3 && yarn --prod
RUN bundle exec rails assets:precompile RAILS_ENV=production SECRET_KEY_BASE=fake_secure_for_compile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment