微服务学习 - 本地构建gcp/buildpacks/builder镜像

概述

Google提供了一套适用于buildpacks的工具,GoogleCloudPlatform/buildpacks ,用于识别业务代码语言,然后使用对应的语言构建工具打包业务代码。

这套工具提供了三种不同的builder实现,其中GCP即是适用于kubernetes环境的builder,也是本文需要制作的对象。

环境说明

  • ubuntu 18.04 64bit
  • CPU core * 4
  • Memory * 8 G

准备工具

整个过程需要需要container-structure-test、Bazel、pack、Docker这些工具,确保这些工具的执行文件处于$PATH目录下。

可以通过以下文档安装对应的组件:

安装container-structure-test请参考 这里
本例中的安装方法在 这里

安装Bazel请参考 这里
本例中的安装方法在 这里

安装pack请参考 这里
本例中的安装方法:

1
curl -sSL "https://github.com/buildpacks/pack/releases/download/v0.18.1/pack-v0.18.1-linux.tgz" | sudo tar -C /usr/local/bin/ --no-same-owner -xzv pack

安装Docker参考 这里
本例中的安装方法:

1
apt install docker.io

可以使用以下命令验证是否已准备好所有依赖:

1
bazel test --test_output=errors tools/checktools:main_test
显示|隐藏输出内容
1
2
3
4
5
6
7
8
9
10
11
12
Starting local Bazel server and connecting to it...
DEBUG: /root/.cache/bazel/_bazel_root/e4b1b9bef0cd3440966c84be2d7ec993/external/io_bazel_rules_go/go/private/context.bzl:281:14: WARNING: rule //tools/checktools:main_test depends on executable //tools/checktools:main via embed. This is not safe for cross-compilation. Depend on go_library instead. This will be an error in the future.
INFO: Analyzed target //tools/checktools:main_test (43 packages loaded, 6950 targets configured).
INFO: Found 1 test target...
Target //tools/checktools:main_test up-to-date:
bazel-bin/tools/checktools/linux_amd64_pure_stripped/main_test
INFO: Elapsed time: 26.994s, Critical Path: 9.71s
INFO: 9 processes: 3 internal, 5 linux-sandbox, 1 local.
INFO: Build completed successfully, 9 total actions
//tools/checktools:main_test PASSED in 0.1s

INFO: Build completed successfully, 9 total actions

创建gcp/base

可以参考 点击这里

或者参考buildpacks/tools/cloudbuild/create_builder.yaml中的步骤

克隆gcp/buildpacks

克隆gcp的buildpacks项目,进入目录:

1
2
git clone https://github.com/GoogleCloudPlatform/buildpacks.git
cd buildpacks

创建stack,即准备build和run镜像

可以先看这里了解 What is a stack?

为了构建builder,需要先准备好build镜像和run镜像,它们的作用分别是:

  • build镜像:在buildpacks的过程中表示build-time,为builder提供运行环境
  • run镜像:在buildpacks的过程中表示run-time,为业务应用提供运行环境

可以通过本地编译上面的这两个镜像,也可以直接拉取这两个镜像:

使用以下命令编译镜像:
:如果docker默认网络为bridge,需要修改builders/gcp/base/stack/build.sh,将其中的docker build替换为docker build --network=host

1
bazel run builders/gcp/base/stack:build

使用以下命令拉取镜像:

1
bazel run tools:pull_images gcp base

创建builder镜像

使用bazel命令创建builder镜像

1
bazel build //builders/gcp/base:builder.image

测试

1
2
3
export product=gcp
export runtime=base
bazel test "builders/${product}/${runtime}/acceptance/..."

License

为gcp/base即builder镜像添加license:

1
./tools/licenses/add.sh gcp/base

验证license,先下载镜像gcr.io/gae-runtimes/license_validator:current,再执行以下命令:

1
docker run --rm gcr.io/gae-runtimes/license_validator:current -pull_images=false gcp/base

更换gcp/base镜像的tag:

1
docker tag gcp/base:latest {YOUR DOCERHUB ID}/buildpacks_builder:v1

上传镜像到指定的仓库:

1
docker push {YOUR DOCERHUB ID}/buildpacks_builder:v1