Running docker build with bazel genrule and a dockerfile

1.4k views Asked by At

I have a monorepo with multiple languages and artifacts and I want to transition to Bazel. We want to build docker images using our existing Dockerfiles, using a genrule - to avoid translating all dockerfiles to docker-rules (at least at this point).

We know it's not Bazel's best practice, but we assumed it can allow us easy transition.

I'm testing with this Dockerfile

FROM alpine:3.8
ENTRYPOINT ["echo"]
CMD ["Hello Bazel!"]

I tried following this post, but when running the docker build command (even out of Bazel) I'm getting this -

> tar -czh . | docker build -t hello-bazel -

[+] Building 0.1s (2/2) FINISHED                                                                                                                        
 => [internal] load remote build context                                                                                                           0.0s
 => ERROR copy /context /                                                                                                                          0.1s
------
 > copy /context /:
------
failed to solve with frontend dockerfile.v0: failed to read dockerfile: Error processing tar file(gzip: invalid header): 

I tried using a genrule with the basic docker build command -

genrule(
    name = "gc-hello-bazel",
    srcs = ["Dockerfile"],
    outs = ["imagesha.txt"],
    cmd = "docker build -t hello-bazel -f $(location Dockerfile) . > $@",
    tools = ["Dockerfile"],
)

But the build fails with

failed to solve with frontend dockerfile.v0: failed to read dockerfile: open Dockerfile: no such file or directory

in case it matters, this is my directory structure:

-WORKSPACE
-<some-root-dirctories>
-<a-root-directory>
    -<subdir>
       -<subsubdir1>
       -my_docker
           -Dockerfile
           -BUILD.bazel

What am I doing wrong?

TL;DR: I'm looking for a working example of docker build with Dockerfile and Bazel's Genrule

1

There are 1 answers

0
silvergasp On

This is not an exact answer to your question as it uses a rule rather than a genrule. But I think it should solve your underlying problem.

Under bazelbuild/rules_docker there is a (non-hermetic) rule for building docker images from a Dockerfile.

To use it you will need to add the following to your WORKSPACE file;

# file: //WORKSPACE
http_archive(
    name = "io_bazel_rules_docker",
    sha256 = "b1e80761a8a8243d03ebca8845e9cc1ba6c82ce7c5179ce2b295cd36f7e394bf",
    urls = ["https://github.com/bazelbuild/rules_docker/releases/download/v0.25.0/rules_docker-v0.25.0.tar.gz"],
)

Then in your build file you can add the following;

# file: BUILD.bazel
load("@io_bazel_rules_docker//contrib:dockerfile_build.bzl", "dockerfile_image")

dockerfile_image(
    name = "my_non_hermetic_image",
    dockerfile = ":Dockerfile",
)