Bazel Docker 容器使用入门

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

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

本部分中的说明可让您使用 Bazel 容器在主机环境中签出的源代码进行构建。系统会为执行的每个 build 命令启动一个容器。构建结果会缓存在宿主环境中,以便在不同构建之间重复使用。

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

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 build 标志来构建带有 Sanitizers 的项目,以相应地选择 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/

执行常规 build。

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

通过添加 --config=asan|tsan|msan build 标志来构建带有 Sanitizers 的项目,以相应地选择 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