Installing private Gems from Gitlab during Docker Build

Dockerize all the things, but what should you do with private gems? Well, lucky you, bundler has already thought about that and has a simple solution.

Installing private Gems from Gitlab during Docker Build

In the progress of moving more and more of our internal tools to Docker, I came across the problem of building docker containers with self-hosted Gems on our gitlab server. I came across this post which gives you several options and the last one using GitHub can be used with gitlab as well. So let's get started.

Create a deploy token in gitlab

Go to your project in gitlab and under Settings -> Repository you can create a deploy token. Create a token with the read_repository scope.

gitlab deploy token

Tell Bundler to use the token

If you look at the bundler docs regarding credentials for gem sources you will find that bundler accepts credentials as an environment variable, which is exactly what we need, this can be done during docker build like this:

docker build -t parse_camt --build-arg BUNDLE_GIT__LCX__AT="<token goes here>:<pass goes here>" .

Basically, add your hostname, capitalized and with __ instead of . so for git.lcx.at I need to pass BUNDLE_GIT__LCX__AT

The Dockerfile

Now all you need to do is pass the environment variable as ARG in Dockerfile for bundle to pick it up.

FROM ruby:2
MAINTAINER LcX
WORKDIR /app
COPY Gemfile* ./
RUN gem install bundler

ARG BUNDLE_GIT__LCX__AT
RUN bundle install

COPY parse_camt.rb ./
CMD ["ruby","/app/parse_camt.rb"]

Run the docker build command mentioned above and you are good to go!