有没有办法设置多个本地 Go 模块,以便它们可以在一个 Docker 容器中运行而无需从 Github 中提取?

埃里克·本特

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

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

|--services
|  |--service1
|     |--Dockerfile
|     |--main.go
|     |--go.mod
|  |--service2
|     |--Dockerfile
|     |--main.go
|     |--go.mod
|--serviceHelper
|  |--serviceHelper.go
|  |--go.mod

我的 Dockerfile 目前只是一个用于 Go 的普通 Dockerfile:

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 并且从那以后了解到您必须将单个模块放入单个工作区文件夹中。我仍然无法在本地配置模块以github.com/gorilla/mux在一项服务中导入普通包和我的本地包。我使用 Apple M1,我希望这也不会引起问题。

我需要如何配置 go.mod 文件、Docker 文件和 Go 导入,以便我既可以在编辑器中正常调试 Go(即 serviceHelper 模块不只是直接加载到 Docker 容器中),也可以运行无需从 github 获取 serviceHelper 就可以在本地完成所有操作?

更新:我已经尝试了很多变体,但是有了这个(感谢您的回答 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 时go mod tidy,会发生此错误(这就是我的意思是“并且在本地运行所有内容而无需从 github 获取 serviceHelper”的错误,因为我之前遇到过此错误):

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,所以这不再是一个问题。

米奇
replace github.com/name/backend/serviceHelper => ../../serviceHelper
...
github.com/name/backend/servicehelper: cannot find module

导入区分大小写。我建议在导入、replace 语句和要导入的包的 go.mod 文件中将所有内容都设为小写。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章