有没有办法设置多个本地 Go 模块,以便它们可以在一个 Docker 容器中运行

因此,我的目标是建立一个本地开发环境,其中多个Go服务(全部作为独立模块)在多个Docker容器和一个Go模块中运行,所有服务都可以用来启动一个连接到数据库等的新服务,而无需在每个模块/服务中重复此代码。


所以我的结构看起来像这样(在$GOPATH/src/github.com/名称/后端/中):


|--services

|  |--service1

|     |--Dockerfile

|     |--main.go

|     |--go.mod

|  |--service2

|     |--Dockerfile

|     |--main.go

|     |--go.mod

|--serviceHelper

|  |--serviceHelper.go

|  |--go.mod

我的泊坞文件目前只是一个普通的 Go 多克文件:


FROM golang:alpine AS build-env

WORKDIR /backend

ADD . /backend

RUN cd /backend && go build -o service1


FROM alpine

RUN apk update && \

   apk add ca-certificates && \

   update-ca-certificates && \

   rm -rf /var/cache/apk/*

WORKDIR /backend

COPY --from=build-env /backend/service1 /backend

EXPOSE 8080

ENTRYPOINT ["./service1"]

我的go.mod文件也只是:


module github.com/name/backend/services/service1


go 1.17

我现在遇到的问题是,你要么必须从github存储库中提取一个模块,我不想这样做,要么将serviceHelper代码放在服务的每个模块中,我也不想这样做。


我使用VSCode,从那以后就知道你必须将单个模块放入单个工作区文件夹中。我仍然无法设法在本地配置模块以在一个服务中导入普通包,例如我的本地包。我使用Apple M1,我希望这可能不会引起问题。github.com/gorilla/mux


我需要如何配置 go.mod 文件、Docker 文件和 Go 导入,以便我可以在编辑器中正常调试 Go(即,服务助手模块不仅直接加载到 Docker 容器中),还可以在本地运行所有内容,而不必从 github 获取服务助手?


更新:我已经尝试了很多变体,但是有了这个(谢谢你的答案colm.anseo),我得到了最少的错误消息,但它仍然试图连接到github,我不想要。因此,更新后的 go.mod 文件如下所示:


module github.com/name/backend/services/service1


go 1.17


require (

    github.com/name/backend/serviceHelper v1.0.0

    github.com/gorilla/mux v1.8.0

)


replace github.com/name/backend/serviceHelper => ../../serviceHelper

然后,当我尝试使用 构建一个新的 go.sum 时,会发生此错误(这就是我所说的错误,“并且还可以在本地运行所有内容,而不必从 github 获取 serviceHelper”,因为我之前遇到过此错误):go mod tidy


github.com/name/backend/servicehelper: cannot find module providing package github.com/name/backend/servicehelper: module github.com/name/backend/servicehelper: git ls-remote -q origin in /Users/myName/go/pkg/mod/cache/vcs/...: exit status 128:

        ERROR: Repository not found.

        fatal: Could not read from remote repository.


        Please make sure you have the correct access rights

        and the repository exists.

我不希望它连接到github,我只希望它在本地运行。在 colm.anseo 的答案的帮助下,我认为我知道如何创建一个有效的 Dockerfile,所以这不再是一个问题了。


HUX布斯
浏览 80回答 2
2回答

慕哥9229398

replace github.com/name/backend/serviceHelper => ../../serviceHelper ... github.com/name/backend/servicehelper: cannot find module导入区分大小写。我建议在导入、替换语句和要导入的包的 go.mod 文件中将所有内容都设为小写。

回首忆惘然

如果您还没有准备好将代码发布到互联网git存储库(如 ),则可以在中使用 replace 指令:github.comgo.modmodule github.com/me/my_appgo 1.17require (    github.om/gorilla/handlers v1.5.1    github.com/me/my_srv1)replace github.com/me/my_srv1 => ./my_srv1在您的Go代码中,您可以导入此代码,就好像它来自互联网一样:// go codeimport (    "github.om/gorilla/handlers"    "github.com/me/my_srv1")在 Docker 上下文中,必须确保在与 相同的相对路径中复制并访问该目录。./my_srv1go buildgo build然后与将一起从互联网上拉取软件包 - 但使用本地开发目录作为您的(尚未发布的)存储库的替代品。go.modgorilla/mux
打开App,查看更多内容
随时随地看视频慕课网APP