首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang Dockerfile :无法在docker构建中找到包,但正常运行

Golang Dockerfile :无法在docker构建中找到包,但正常运行
EN

Stack Overflow用户
提问于 2019-04-25 13:04:31
回答 1查看 2.9K关注 0票数 1

我为我的golang微服务项目提供了以下多阶段构建的dockerfile设置

代码语言:javascript
复制
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中有以下导入

代码语言:javascript
复制
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 .时,我得到以下错误

代码语言:javascript
复制
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总结

代码语言:javascript
复制
    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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-25 16:00:31

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

完整的Dockerfile示例:

代码语言:javascript
复制
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版本更改为特定的最新版本,如上面的示例所示。我以前遇到过哥朗版的问题。但是您所得到的错误是因为容器中不存在go.mod文件。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55849976

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档