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


文件

去.mod


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


go 1.16


require github.com/gammazero/workerpool v1.1.2

Dockerfile


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 build 时,我在 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