Search code examples
dockerbazel

Add Bazel to a docker image


We are migrating an existing project to Bazel, and we are facing the following situation:

The project is rather large, and we want to transition gradually; during that gradual transition both our old build approach and Bazel should work; our current system creates docker images out of our project and then runs tests and other validations in those docker containers. So to add Bazel, we seem to have to be able to run Bazel inside those docker containers as well.

Is there a way to add Bazel into existing docker files such that we don't download the components we don't need to download, and such that we can store the resulting image in our company's repository?

By now, I have seen a lot of instructions on how to build docker images using bazel and I have also found an old bazel image by google with lots of tools we don't need, and the repository itself had been archived.


Solution

  • It's fairly easy to do something like that. While you could just copy paste in the installation instructions into an Ubuntu Docker file, I'd strongly recommend using bazelisk. e.g. something like this should work (untested);

    FROM ubuntu:20.04
    
    # NOTE 'g++ unzip zip' are required by bazel
    RUN apt update && apt install wget g++ unzip zip
    
    RUN wget https://github.com/bazelbuild/bazelisk/releases/download/v1.15.0/bazelisk-linux-amd64 && \
        chmod 755 bazelisk-linux-amd64 && \
        mv bazelisk-linux-amd64 /usr/bin/bazelisk
    
    # Download some of the other tools that you explicitly need...
    
    RUN mkdir /workspace
    
    WORKDIR /workspace
    
    USER bazel
    
    # other setup...
    

    Now to get the most out of bazelisk, you'll need to add a file .bazelversion to your workspace. e.g.

    6.0.0
    

    Now when you run bazelisk (e.g. bazelisk build //... from your docker container bazelisk will;

    • Download and extract bazel version 6.0.0
    • Run bazel 6.0.0 and build all targets under //...

    NOTE: Bazel does depend on some system deps, which won't be covered by the bazelisk install. But you can choose which system deps you will likely use with bazel.