Dockerizing Go API 在不设置 git 项目 repo 的情况下无法工作

我有一个非常简单的项目 - 一个具有以下目录结构的 Go API


├── Dockerfile

├── go.mod

├── go.sum

├── main.go

└── user

    ├── repository.go

    └── user.go

我的 Dockerfile 看起来像这样


FROM golang:1.17-alpine

WORKDIR /app

COPY go.mod ./

COPY go.sum ./

RUN go mod download

COPY *.go ./

RUN go build -o /api

CMD [ "/api" ]

我不断收到这个错误:


[7/7] RUN go build -o /api: #11 0.462 main.go:4:2: 包 api/user 不在 GOROOT (/usr/local/go/src/api/user)


在阅读了一下之后,看起来我可能需要设置一个 github 存储库并从 git 中提取代码?我认为这真的很疯狂,因为代码就在 Docker 映像中。


如何在不设置 git repo 的情况下构建/Dockerize 这个 Go 项目github.com/alex/someproject?问是因为我不想将其发布到 github 上——这在本地应该很简单。


GCT1015
浏览 72回答 1
1回答

鸿蒙传说

你不需要将你的 Go 代码发布到像 github.com 这样的服务上来编译它。您需要做的就是确保您要编译的代码在您正在编译它的机器上。您的go build命令失败,因为错误消息中提到的包在机器上找不到。以下假设 Go 项目本身是有序的,您可以在本地机器上编译它。如果不是这种情况,并且后面的答案不能帮助您解决问题,那么您需要在问题中包含更多信息,例如go.mod文件、main.go文件以及user包的内容。请注意,COPY *.go ./它不会递归地复制所有 go 文件,即它不会复制目录中的./user/文件。COPY:每个都<src>可能包含通配符,并且将使用 Go 的&nbsp;filepath.Match规则进行匹配。filepath.Match:模式语法是:pattern:&nbsp; { term }term:&nbsp; '*'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;matches any sequence of non-Separator characters&nbsp; '?'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;matches any single non-Separator character&nbsp; '[' [ '^' ] { character-range } ']'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; character class (must be non-empty)&nbsp; c&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;matches character c (c != '*', '?', '\\', '[')&nbsp; '\\' c&nbsp; &nbsp; &nbsp; matches character ccharacter-range:&nbsp; c&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;matches character c (c != '\\', '-', ']')&nbsp; '\\' c&nbsp; &nbsp; &nbsp; matches character c&nbsp; lo '-' hi&nbsp; &nbsp;matches character c for lo <= c <= hi请注意,该'*'术语匹配任何非分隔符字符序列,这意味着由于分隔符*.go而不会匹配。foo/bar.go/在您的 中包含以下内容就足够了Dockerfile:FROM golang:1.17-alpineWORKDIR /appCOPY . ./RUN go build -o /apiCMD [ "/api" ]但是,如果您想对您复制的文件有选择性,那么您可以这样做:COPY go.mod ./COPY go.sum ./COPY user/ ./user/COPY *.go ./
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go