Bazel Docker 容器使用入门

报告问题 查看源代码

本页面详细介绍了 Bazel 容器的内容,如何使用 Bazel 容器内的 Bazel 构建 abseil-cpp 项目,以及如何使用具有目录装载功能的 Bazel 容器直接从主机构建此项目。

通过目录装载从主机构建 Abseil 项目

通过本部分中的说明,您可以使用 Bazel 容器进行构建,其中包含在托管环境中签出的来源。系统会为您执行的每个构建命令启动一个容器。构建结果会缓存在托管环境中,以便在构建之间重复使用。

将项目克隆到宿主机的目录中。

git clone https://github.com/abseil/abseil-cpp.git /src/workspace

创建一个文件夹,用于存放要在各 build 之间共享的缓存结果。

mkdir -p /tmp/build_output/

使用 Bazel 容器构建项目,并在宿主机的输出文件夹中提供构建输出。

docker run \
  -e USER="$(id -u)" \
  -u="$(id -u)" \
  -v /src/workspace:/src/workspace \
  -v /tmp/build_output:/tmp/build_output \
  -w /src/workspace \
  gcr.io/bazel-public/bazel:latest \
  --output_user_root=/tmp/build_output \
  build //absl/...

使用排错程序构建项目,方法是添加 --config=asan|tsan|msan 构建标志,以相应地选择 AddressSanitizer (asan)、ThreadSanitizer (tsan) 或 MemorySanitizer (msan)。

docker run \
  -e USER="$(id -u)" \
  -u="$(id -u)" \
  -v /src/workspace:/src/workspace \
  -v /tmp/build_output:/tmp/build_output \
  -w /src/workspace \
  gcr.io/bazel-public/bazel:latest \
  --output_user_root=/tmp/build_output \
  build --config={asan | tsan | msan} -- //absl/... -//absl/types:variant_test

在容器内构建 Abseil 项目

通过本部分中的说明,您可以使用 Bazel 容器(容器内部有来源)进行构建。通过在开发工作流开始时启动容器并在容器内进行更改,可以缓存构建结果。

在 Bazel 容器中启动 shell:

docker run --interactive --entrypoint=/bin/bash gcr.io/bazel-public/bazel:latest

每个容器 ID 都是唯一的。在以下说明中,容器为 5a99103747c6。

克隆项目。

root@5a99103747c6:~# git clone https://github.com/abseil/abseil-cpp.git && cd abseil-cpp/

执行常规构建。

root@5a99103747c6:~/abseil-cpp# bazel build //absl/...

使用排错程序构建项目,方法是添加 --config=asan|tsan|msan build 标志,以相应地选择 AddressSanitizer (asan)、ThreadSanitizer (tsan) 或 MemorySanitizer (msan)。

root@5a99103747c6:~/abseil-cpp# bazel build --config=--config={asan | tsan | msan} -- //absl/... -//absl/types:variant_test

探索 Bazel 容器

在 Bazel 容器内启动交互式 shell(如果尚未启动)。

docker run -it --entrypoint=/bin/bash gcr.io/bazel-public/bazel:latest
root@5a99103747c6:/#

浏览容器内容。

root@5a99103747c6:/# clang --version
clang version 8.0.0 (trunk 340178)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/local/bin
root@5a99103747c6:/# java -version
openjdk version "1.8.0_181"
OpenJDK Runtime Environment (build 1.8.0_181-8u181-b13-0ubuntu0.16.04.1-b13)
OpenJDK 64-Bit Server VM (build 25.181-b13, mixed mode)
root@5a99103747c6:/# python -V
Python 2.7.12
root@5a99103747c6:/# python3 -V
Python 3.6.6
root@5a99103747c6:/# bazel version
Extracting Bazel installation...
Build label: 6.0.0
Build target: bazel-out/k8-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Mon Dec 19 15:52:35 2022 (1671465155)
Build timestamp: 1671465155
Build timestamp as int: 1671465155