3

Let me start by saying I'm new to Bazel. I am trying to build a Docker container from a golang project that contains local module references.

First I'm creating a local golang module:

go mod init go-example

Here is the general project structure:

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

In main.go I am importing pkg/echo from the local module.

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

...

# gazelle:prefix go-example

✅ Default bazel build works

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

❌ Docker build fails. I get the following error:

(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.
hampusohlsson
  • 10,109
  • 5
  • 33
  • 50

1 Answers1

1

Figured it out, posting here if anyone else stumbles on this.

The answer is simple - you need to embed the go_library rule within the go_image rule. Here is my cmd/hello/BUILD.bazel where I also embed the go image in a docker container

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",
)

Now it works to run bazel build //cmd/hello:docker

hampusohlsson
  • 10,109
  • 5
  • 33
  • 50