Bazel 使用本地 golang 模块构建 docker 容器

Bazel build docker container with local golang module

首先让我说我是 Bazel 的新手。我正在尝试从包含本地模块引用的 golang 项目构建一个 Docker 容器。

首先我要创建一个本地 golang 模块:

go mod init go-example

这里是一般的项目结构:

.
├── BUILD.bazel
├── WORKSPACE
├── cmd
│   └── hello
│       ├── BUILD.bazel
│       └── main.go
├── go.mod
├── go.sum
└── pkg
    └── echo
        ├── BUILD.bazel
        └── echo.go

main.go 中,我从本地模块导入 pkg/echo

import (
    "go-example/pkg/echo"
)
(top level BUILD.bazel)

...

# gazelle:prefix go-example

✅ 默认 bazel 构建有效

$ bazel run //:gazelle
$ bazel build //cmd/hello 

❌ Docker 构建失败。我收到以下错误:

(cmd/hello/BUILD.bazel)

...

go_image(
    name = "docker",
    srcs = ["main.go"],
    importpath = "go-example/cmd/hello",
)
$ bazel build //cmd/hello:docker
...
compilepkg: missing strict dependencies:
    /private/var/tmp/_bazel[...]/__main__/cmd/hello/main.go: import of "go-example/pkg/echo"
No dependencies were provided.

弄清楚了,如果其他人偶然发现了这个,请在​​这里发帖。

答案很简单 - 您需要将 go_library 规则嵌入到 go_image 规则中。这是我的 cmd/hello/BUILD.bazel,我还将 go 图像嵌入 docker 容器

load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
load("@io_bazel_rules_docker//go:image.bzl", "go_image")
load("@io_bazel_rules_docker//container:container.bzl", "container_image")

go_library(
    name = "hello_lib",
    srcs = ["main.go"],
    importpath = "go-example/cmd/hello",
    visibility = ["//visibility:private"],
    deps = ["//pkg/echo"],
)

go_binary(
    name = "hello",
    embed = [":hello_lib"],
    visibility = ["//visibility:public"],
)

go_image(
    name = "hello_go_image",
    embed = [":hello_lib"],
    goarch = "amd64",
    goos = "linux",
    pure = "on",
)

container_image(
    name = "docker",
    base = ":hello_go_image",
)

现在适用于 运行 bazel build //cmd/hello:docker