rules_docker

rules_docker

Bazel规则集简化Docker容器构建与管理

rules_docker是一套Bazel规则集,用于构建和管理Docker容器。它无需使用Docker即可拉取基础镜像、增强构建产物和发布镜像。该项目支持Python、Java、Go等多种语言的容器化规则,简化了应用程序容器化过程。虽然目前已停止维护,rules_docker仍是一个功能完善的容器化工具,值得开发者了解和参考。

Bazel容器镜像规则Docker构建容器持续集成Github开源项目

Bazel Container Image Rules

Bazel CI
Build status

Status

🚨 rules_docker is no longer maintained and deprecated. Please see rules_oci for a better designed and maintained alternative.

Basic Rules

These rules used to be docker_build, docker_push, etc. and the aliases for these (mostly) legacy names still exist largely for backwards-compatibility. We also have early-stage oci_image, oci_push, etc. aliases for folks that enjoy the consistency of a consistent rule prefix. The only place the format-specific names currently do any more than alias things is in foo_push, where they also specify the appropriate format as which to publish the image.

Overview

This repository contains a set of rules for pulling down base images, augmenting them with build artifacts and assets, and publishing those images. These rules do not require / use Docker for pulling, building, or pushing images. This means:

  • They can be used to develop Docker containers on OSX without boot2docker or docker-machine installed. Note use of these rules on Windows is currently not supported.
  • They do not require root access on your workstation.

Also, unlike traditional container builds (e.g. Dockerfile), the Docker images produced by container_image are deterministic / reproducible.

To get started with building Docker images, check out the examples that build the same images using both rules_docker and a Dockerfile.

NOTE: container_push and container_pull make use of google/go-containerregistry for registry interactions.

Language Rules

It is notable that: cc_image, go_image, rust_image, and d_image also allow you to specify an external binary target.

Docker Rules

This repo now includes rules that provide additional functionality to install packages and run commands inside docker containers. These rules, however, require a docker binary is present and properly configured. These rules include:

Overview

In addition to low-level rules for building containers, this repository provides a set of higher-level rules for containerizing applications. The idea behind these rules is to make containerizing an application built via a lang_binary rule as simple as changing it to lang_image.

By default these higher level rules make use of the distroless language runtimes, but these can be overridden via the base="..." attribute (e.g. with a container_pull or container_image target).

Note also that these rules do not expose any docker related attributes. If you need to add a custom env or symlink to a lang_image, you must use container_image targets for this purpose. Specifically, you can use as base for your lang_image target a container_image target that adds e.g., custom env or symlink. Please see <a href=#go_image-custom-base>go_image (custom base)</a> for an example.

Setup

Add the following to your WORKSPACE file to add the external repositories:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( # Get copy paste instructions for the http_archive attributes from the # release notes at https://github.com/bazelbuild/rules_docker/releases ) # OPTIONAL: Call this to override the default docker toolchain configuration. # This call should be placed BEFORE the call to "container_repositories" below # to actually override the default toolchain configuration. # Note this is only required if you actually want to call # docker_toolchain_configure with a custom attr; please read the toolchains # docs in /toolchains/docker/ before blindly adding this to your WORKSPACE. # BEGIN OPTIONAL segment: load("@io_bazel_rules_docker//toolchains/docker:toolchain.bzl", docker_toolchain_configure="toolchain_configure" ) docker_toolchain_configure( name = "docker_config", # OPTIONAL: Bazel target for the build_tar tool, must be compatible with build_tar.py build_tar_target="<enter absolute path (i.e., must start with repo name @...//:...) to an executable build_tar target>", # OPTIONAL: Path to a directory which has a custom docker client config.json. # See https://docs.docker.com/engine/reference/commandline/cli/#configuration-files # for more details. client_config="<enter Bazel label to your docker config.json here>", # OPTIONAL: Path to the docker binary. # Should be set explicitly for remote execution. docker_path="<enter absolute path to the docker binary (in the remote exec env) here>", # OPTIONAL: Path to the gzip binary. gzip_path="<enter absolute path to the gzip binary (in the remote exec env) here>", # OPTIONAL: Bazel target for the gzip tool. gzip_target="<enter absolute path (i.e., must start with repo name @...//:...) to an executable gzip target>", # OPTIONAL: Path to the xz binary. # Should be set explicitly for remote execution. xz_path="<enter absolute path to the xz binary (in the remote exec env) here>", # OPTIONAL: Bazel target for the xz tool. # Either xz_path or xz_target should be set explicitly for remote execution. xz_target="<enter absolute path (i.e., must start with repo name @...//:...) to an executable xz target>", # OPTIONAL: List of additional flags to pass to the docker command. docker_flags = [ "--tls", "--log-level=info", ], ) # End of OPTIONAL segment. load( "@io_bazel_rules_docker//repositories:repositories.bzl", container_repositories = "repositories", ) container_repositories() load("@io_bazel_rules_docker//repositories:deps.bzl", container_deps = "deps") container_deps() load( "@io_bazel_rules_docker//container:container.bzl", "container_pull", ) container_pull( name = "java_base", registry = "gcr.io", repository = "distroless/java", # 'tag' is also supported, but digest is encouraged for reproducibility. digest = "sha256:deadbeef", )

Known Issues

  • Bazel does not deal well with diamond dependencies.

If the repositories that are imported by container_repositories() have already been imported (at a different version) by other rules you called in your WORKSPACE, which are placed above the call to container_repositories(), arbitrary errors might occur. If you get errors related to external repositories, you will likely not be able to use container_repositories() and will have to import directly in your WORKSPACE all the required dependencies (see the most up to date impl of container_repositories() for details).

  • ImportError: No module named moves.urllib.parse

This is an example of an error due to a diamond dependency. If you get this error, make sure to import rules_docker before other libraries, so that six can be patched properly.

See https://github.com/bazelbuild/rules_docker/issues/1022 for more details.

  • Ensure your project has a BUILD or BUILD.bazel file at the top level. This can be a blank file if necessary. Otherwise you might see an error that looks like:
Unable to load package for //:WORKSPACE: BUILD file not found in any of the following directories.
  • rules_docker uses transitions to build your containers using toolchains the correct architecture and operating system. If you run into issues with toolchain resolutions, you can disable this behaviour, by adding this to your .bazelrc:
build --@io_bazel_rules_docker//transitions:enable=false

Using with Docker locally.

Suppose you have a container_image target //my/image:helloworld:

container_image( name = "helloworld", ... )

You can load this into your local Docker client by running: bazel run my/image:helloworld.

For the lang_image targets, this will also run the container using docker run to maximize compatibility with lang_binary rules.

Arguments to this command are forwarded to docker, meaning the command

bazel run my/image:helloworld -- -p 8080:80 -- arg0

performs the following steps:

  • load the my/image:helloworld target into your local Docker client
  • start a container using this image where arg0 is passed to the image entrypoint
  • port forward 8080 on the host to port 80 on the container, as per docker run documentation

You can suppress this behavior by passing the single flag: bazel run :foo -- --norun

Alternatively, you can build a docker load compatible bundle with: bazel build my/image:helloworld.tar. This will produce a tar file in your bazel-out directory that can be loaded into your local Docker client. Building this target can be expensive for large images. You will first need to query the ouput file location.

TARBALL_LOCATION=$(bazel cquery my/image:helloworld.tar \ --output starlark \ --starlark:expr="target.files.to_list()[0].path") docker load -i $TARBALL_LOCATION

These work with both container_image, container_bundle, and the lang_image rules. For everything except container_bundle, the image name will be bazel/my/image:helloworld. The container_bundle rule will apply the tags you have specified.

Authentication

You can use these rules to access private images using standard Docker authentication methods. e.g. to utilize the Google Container Registry. See here for authentication methods.

See also:

Once you've setup your docker client configuration, see here for an example of how to use container_pull with custom docker authentication credentials and here for an example of how to use container_push with custom docker authentication credentials.

Varying image names

A common request from folks using container_push, container_bundle, or container_image is to be able to vary the tag that is pushed or embedded. There are two options at present for doing this.

Stamping

The first option is to use stamping. Stamping is enabled when bazel is run with --stamp. This enables replacements in stamp-aware attributes. A python format placeholder (e.g. {BUILD_USER}) is replaced by the value of the corresponding workspace-status variable.

# A common pattern when users want to avoid trampling # on each other's images during development. container_push( name = "publish", format = "Docker", # Any of these components may have variables. registry = "gcr.io", repository = "my-project/my-image", # This will be replaced with the current user when built with --stamp tag = "{BUILD_USER}", )

Rules that are sensitive to stamping can also be forced to stamp or non-stamp mode irrespective of the --stamp flag to Bazel. Use the build_context_data rule to make a target that provides StampSettingInfo, and pass this to the build_context_data attribute.

The next natural question is: "Well what variables can I use?" This option consumes the workspace-status variables Bazel defines in bazel-out/stable-status.txt and bazel-out/volatile-status.txt.

Note that changes to the stable-status file cause a rebuild of the action, while volatile-status does not.

You can add more stamp variables via --workspace_status_command, see the bazel docs. A common example is to provide the current git SHA, with --workspace_status_command="echo STABLE_GIT_SHA $(git rev-parse HEAD)"

That flag is typically passed in the .bazelrc file, see for example .bazelrc in kubernetes.

Make variables

The second option is to employ Makefile-style variables:

container_bundle( name = "bundle", images = { "gcr.io/$(project)/frontend:latest": "//frontend:image", "gcr.io/$(project)/backend:latest": "//backend:image", } )

These variables are specified on the CLI using:

bazel build --define project=blah //path/to:bundle

Debugging lang_image rules

By default the lang_image rules use the distroless base runtime images, which are optimized to be the minimal set of things your application needs at runtime. That can make debugging these containers difficult because they lack even a basic shell for exploring the filesystem.

To address this, we publish variants of the distroless runtime images tagged :debug, which are the exact-same images, but with additions such as busybox to make debugging easier.

For example (in this repo):

$ bazel run -c dbg testdata:go_image ... INFO: Build completed successfully, 5 total actions INFO: Running command line: bazel-bin/testdata/go_image Loaded image ID: sha256:9c5c2167a1db080a64b5b401b43b3c5cdabb265b26cf7a60aabe04a20da79e24 Tagging 9c5c2167a1db080a64b5b401b43b3c5cdabb265b26cf7a60aabe04a20da79e24 as bazel/testdata:go_image Hello, world! $ docker run -ti --rm --entrypoint=sh bazel/testdata:go_image -c "echo Hello, busybox." Hello, busybox.

Examples

container_image

container_image( name = "app", # References container_pull from WORKSPACE (above) base = "@java_base//image", files = ["//java/com/example/app:Hello_deploy.jar"], cmd = ["Hello_deploy.jar"] )

Hint: if you want to put files in specific directories inside the image use <a href="https://docs.bazel.build/versions/master/be/pkg.html">pkg_tar rule</a> to create the desired directory structure and pass that to container_image via tars attribute. Note you might need to set strip_prefix = "." or strip_prefix = "{some directory}" in your rule for the files to not be flattened. See <a href="https://github.com/bazelbuild/bazel/issues/2176">Bazel upstream issue 2176</a> and <a href="https://github.com/bazelbuild/rules_docker/issues/317">rules_docker issue 317</a> for more details.

cc_image

To use cc_image, add the following to WORKSPACE:

load( "@io_bazel_rules_docker//repositories:repositories.bzl", container_repositories = "repositories", ) container_repositories() load(

编辑推荐精选

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多