登录
首页 >  Golang >  Go问答

创建 docker 容器来运行“go test”,并下载并缓存所有模块依赖项

来源:stackoverflow

时间:2024-04-15 19:15:36 307浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《创建 docker 容器来运行“go test”,并下载并缓存所有模块依赖项》,聊聊,我们一起来看看吧!

问题内容

我想在需要使用 docker 的 ci 环境中测试我的 go 代码。如何创建一个 docker 映像,该映像已下载并编译了 go.mod 中列出的所有依赖项,以便 docker run $img go test 使用缓存的工件?

该图像所需的属性:

  • 该镜像仅使用 go.mod 来编译依赖项。我不想使用完整的源代码,因为对源代码的任何更改都会使保存缓存依赖项的 docker 层失效。

  • docker run $img go test ./... 不会重新下载或重新编译 go.mod 中列出的依赖项。

  • 避免实验性 docker 功能。

现有方法

解析 go.mod 并使用 go get

来自https://github.com/golang/go/issues/27719#issuecomment-578246826

这种方法很接近,但当我运行 go test 时,它似乎没有使用 gocache。这似乎也会在某些模块路径上阻塞,例如 gopkg.in/datadog/dd-trace-go.v1

from golang:1.13
workdir /src
copy go.mod ./
run set -eu \
  && go mod graph \
  | cut -d '@' -f 1 \
  | cut -d ' ' -f 2 \
  | sort -u \
  | sed -e 's#dd-trace-go.v1#&/ddtrace#' \
  | xargs go get -v
docker run --mount /src:/src $img go test ./...

使用带有挂载缓存的 docker_buildkit

最初描述于 https://github.com/golang/go/issues/27719#issuecomment-514747274。这仅适用于 go build。我无法将它用于 go test,因为缓存挂载在 run 命令之后被卸载,因此它不存在于创建的 docker 映像中。

这也取决于实验性的 docker 功能。

# syntax = docker/dockerfile:experimental
FROM golang:1.13 as go-builder
ARG VERSION
WORKDIR /src
COPY . /src/
# With a mount cache, Docker will cache the target directories for future
# invocations of this RUN layer. Meaning, once this command is run once, all
# successive calls will use the already downloaded and already compiled assets.
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    go build ./server

解决方案


我经常将 copy go.mod 放在 dockerfile 的开头,因为它不会经常更改。

FROM golang:1.14.3 as builder

WORKDIR /app

COPY go.mod .
COPY go.sum .

RUN go mod download

COPY . .
RUN go build -tags netgo -ldflags '-extldflags "-static"' -o app .

FROM centos:7  
WORKDIR /root

COPY --from=builder /app/app .

因此,如果您的 go mod 没有更改,则 run go mod download 行仅在第一次运行。

终于介绍完啦!小伙伴们,这篇关于《创建 docker 容器来运行“go test”,并下载并缓存所有模块依赖项》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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