登录
首页 >  Golang >  Go问答

Golang Dockerfile:无法在docker build中找到包但运行正常

来源:stackoverflow

时间:2024-04-09 11:54:35 433浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《Golang Dockerfile:无法在docker build中找到包但运行正常》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

我有以下 dockerfile 设置用于我的 golang 微服务项目的多阶段构建

from golang:alpine as builder

run apk --no-cache add git

workdir /app/vessel-service

copy . .

run go mod download
run cgo_enabled=0 goos=linux go build -a -installsuffix cgo -o vessel-service

# second stage
...

我的 main.go 中有以下导入内容

import (
  "context"
  "errors"
  "fmt"

  pb "github.com/thededlier/go-micro-shippy/vessel-service/proto/vessel"
  micro "github.com/micro/go-micro"
)

其中的容器服务用于当前项目。

运行 docker build -t vessel-service . 时出现以下错误

step 5/12 : run go mod download
 ---> running in 1d0121039462
warning: pattern "all" matched no module dependencies
removing intermediate container 1d0121039462
 ---> b66add421d26
step 6/12 : run cgo_enabled=0 goos=linux go build -a -installsuffix cgo -o vessel-service
 ---> running in ef50eff44a3b
main.go:9:3: cannot find package "github.com/micro/go-micro" in any of:
  /usr/local/go/src/github.com/micro/go-micro (from $goroot)
  /go/src/github.com/micro/go-micro (from $gopath)
main.go:8:3: cannot find package "github.com/thededlier/go-micro-shippy/vessel-service/proto/vessel" in any of:
  /usr/local/go/src/github.com/thededlier/go-micro-shippy/vessel-service/proto/vessel (from $goroot)
  /go/src/github.com/thededlier/go-micro-shippy/vessel-service/proto/vessel (from $gopath)

但我确实有 ~/go/src/github.com/micro/go-micro。尝试直接运行 main.go 时,它运行没有任何问题。

这是我的环境设置问题还是还有其他问题?

这是我的 go.mod 的摘要

module github.com/thededlier/go-micro-shippy

    go 1.12

    require (
      ...
      github.com/micro/go-micro v1.1.0
      ...
    )
    replace github.com/testcontainers/testcontainer-go => github.com/testcontainers/testcontainers-go v0.0.0-20190108154635-47c0da630f72

    replace sourcegraph.com/sourcegraph/go-diff => github.com/sourcegraph/go-diff v0.5.1

    replace github.com/golang/lint => golang.org/x/lint v0.0.0-20190409202823-959b441ac422

    replace github.com/Sirupsen/logrus => github.com/sirupsen/logrus v1.4.1

解决方案


您需要将 go.mod 文件和 go.sum 文件复制到容器中,并将 env 变量 go111module 设置为 on,如下所示:env go111module=on

完整的 dockerfile 示例:

FROM golang:1.12

ENV GO111MODULE=on
ENV PORT=8090
WORKDIR /app

COPY go.mod .
COPY go.sum .

RUN go mod download

COPY . .

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build

EXPOSE 8090
ENTRYPOINT ["/app/your-app-name"]

如果仍然不起作用,请尝试将 golang 版本更改为特定的最新版本,如上例所示。我之前用 golang 版本也遇到过这个问题。但您收到的错误是因为容器中不存在 go.mod 文件。

理论要掌握,实操不能落!以上关于《Golang Dockerfile:无法在docker build中找到包但运行正常》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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