登录
首页 >  Golang >  Go问答

利用 GitLab 子组中托管的私有 Go 包创建 Docker 镜像的方法

来源:stackoverflow

时间:2024-02-26 19:36:22 435浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《利用 GitLab 子组中托管的私有 Go 包创建 Docker 镜像的方法》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在开发一个导入私有包的 go 项目。私有包存储库位于 gitlab 的一个子组内。我使用 ~/.netrc 文件设置了开发环境并设置 goprivate="gitlab.mycompany.io" ,一切正常。

但是,在 docker 构建期间运行 go mod download 总是失败。

真正奇怪的是,如果我构建一个包含 run go mod download 之前的所有步骤的容器,我可以以交互方式运行该容器并在容器内执行 go mod download ,不会出现任何问题。

这是我的 dockerfile 的样子:

from golang:latest as builder

# adds .netrc
arg netrc
run echo $netrc > ~/.netrc
env goprivate="gitlab.mycompany.io/*"
arg ssh_private_key
run mkdir ~/.ssh && echo "host *\n\tstricthostkeychecking no\n\n" > ~/.ssh/config
run echo "$ssh_private_key" > ~/.ssh/id_rsa && chmod 0600 ~/.ssh/id_rsa

workdir /app
copy . .

run go mod download && go mod verify
run goos=linux goarch=amd64 cgo_enabled=0 go build -ldflags="-w -s"


# from scratch (...etc.)

我使用以下命令运行此命令,其中 netrcssh_private_key 包含这些文件的 cat 输出。

docker build --no-cache --build-arg netrc=$netrc --build-arg ssh_private_key=$ssh_private_key -t test-downloader .

dockerfile 失败并显示:

remote: 
        remote: ========================================================================
        remote: 
        remote: the project you were looking for could not be found.
        remote: 
        remote: ========================================================================
        remote: 
        fatal: could not read from remote repository.

        please make sure you have the correct access rights
        and the repository exists.

谁能帮我理解:

  1. docker 将命令作为构建步骤运行时的环境与我以交互方式运行容器时的环境有区别吗?
  2. 如何进行这项工作? :)

其他信息:

  1. .netrc、.gitconfig 和 ssh 密钥看起来就像在容器内一样。
  2. 我尝试使用 .git-credentials 和 git url 进行身份验证(在 git 配置中使用 insteadof)。这会失败并出现相同的错误,并且当我在包含所有前述步骤的容器内运行 go mod download 时也会失败。
  3. 我尝试在 go.mod 文件中使用各种替换指令,以便将 mod 指向正确的包,其中一种尝试是:
...
    gopkg.in/yaml.v2 v2.2.7
)

replace gitlab.mycompany.io/maingroup/subgroup/myapp v0.0.0 => gitlab.mycompany.io/maingroup/subgroup/myapp.git v0.0.0

解决方案


对我有用的替代解决方案

也许不是您正在寻找的答案,但对我有用的一种方法是不要尝试在 dockerfile 中执行任何类型的身份验证或凭证内容,并继续供应应用程序。我个人不喜欢必须有一个供应商文件夹,但这比必须在 docker 中处理身份验证要好。

您可以在 docker 命令之外运行 go mod tidygo modvendor,提交该命令,然后您的 dockerfile 将如下所示(路径和工作目录可能不是正确的,相关部分是如何构建): p>

FROM golang:1.13-alpine AS build-stage

WORKDIR /app

COPY . /app
RUN go build -mod=vendor

# Final Stage
FROM alpine

RUN mkdir /app
WORKDIR /app

# Copy only the binary so that your Docker image does not have the uncompiled code.
COPY --from=build-stage  /app/APP_NAME .

EXPOSE 3000

ENTRYPOINT ./APP_NAME

我没有尝试过的更干净的解决方案

另一个解决方案是弄清楚如何使用 goproxy。我还没有尝试过该解决方案,但这将是一种更干净的方法。您可以使用类似 athens 的号码:https://docs.gomods.io/configuration/authentication/

以上就是《利用 GitLab 子组中托管的私有 Go 包创建 Docker 镜像的方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>