无法 docker 使用内部包构建 Golang 项目

Can't docker build a Golang project with internal packages

我正在尝试构建一个 Golang 项目,其中包含不同级别的包。我在这里上传了一个示例项目:https://github.com/David-Lor/archive.org-telegrambot/tree/example-go-dockerfile-not-building

文件

go.mod

module github.com/David-Lor/go-example

go 1.16

require github.com/gammazero/workerpool v1.1.2

Docker 文件

FROM golang:1.17.7

WORKDIR /app
COPY ./src/go.mod .
COPY ./src/go.sum .
RUN go mod download


COPY ./src/* ./
#RUN ls -lah # files are copied correctly; go.mod and main.go are in current directory
RUN go build -o /tmp/built

错误

当我 docker 构建时,在 go build 命令中出现以下错误:

Step 7/7 : RUN go build -o /tmp/built
 ---> Running in 72358fb165c4
main.go:8:2: no required module provides package github.com/David-Lor/go-example/internal/foo; to add it:
        go get github.com/David-Lor/go-example/internal/foo
main.go:9:2: no required module provides package github.com/David-Lor/go-example/internal/foo/bar; to add it:
        go get github.com/David-Lor/go-example/internal/foo/bar
The command '/bin/sh -c go build -o /tmp/built' returned a non-zero code: 1

但是,如果我 运行 基础 docker 图像并从那里构建或 运行 应用程序,它工作正常(从主机系统 运行也很好):

$ sudo docker run -it --rm -v $(pwd):/data golang:1.17.7
root@e468a186536f:/go# cd /data/src
root@e468a186536f:/data/src# go build -o /tmp/built
go: downloading github.com/gammazero/workerpool v1.1.2
go: downloading github.com/gammazero/deque v0.1.0
root@e468a186536f:/data/src# /tmp/built
internal/foo
internal/foo/bar
root@e468a186536f:/data/src# go run main.go
internal/foo
internal/foo/bar

问题出在你的Dockerfile;运行后COPY ./src/* ./你的镜像中的目录结构如下:

ZZ> docker run -it d1fae37bbfb1 /bin/sh
# cd /app
# ls -al
total 2048
drwxr-xr-x 1 root root    4096 Feb 16 19:58 .
drwxr-xr-x 1 root root    4096 Feb 16 19:59 ..
drwxr-xr-x 3 root root    4096 Feb 16 19:52 foo
-rwxr-xr-x 1 root root      97 Feb 16 19:57 go.mod
-rwxr-xr-x 1 root root     352 Feb 16 19:52 go.sum
-rwxr-xr-x 1 root root     295 Feb 16 19:52 main.go
# ls foo
bar  foo.go

所以没有 internal 文件夹,这就是构建失败的原因。

如果将此行更改为:

,构建将成功完成

COPY src ./