简体   繁体   中英

'No required module provides package' when building Go docker image

My Dockerfile is below:

# syntax=docker/dockerfile:1

FROM golang:1.18-alpine

WORKDIR /app

COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY *.go ./

RUN go build -o /datapuller

EXPOSE 8080

CMD [ "/datapuller" ]

I tried to build with $ docker build --tag datapuller.

But got error:

main.go:13:2: no required module provides package gitlab.com/mycorp/mycompany/data/datapuller/dbutil; to add it:
        go get gitlab.com/mycorp/mycompany/data/datapuller/dbutil
main.go:14:2: no required module provides package gitlab.com/mycorp/mycompany/data/datapuller/models; to add it:
        go get gitlab.com/mycorp/mycompany/data/datapuller/models

How to solve this, I can run directly with go run main.go just fine.

My main.go 's import is below. I think the imports caused this problem:

package main

import (
    "encoding/json"

    client "github.com/bozd4g/go-http-client"
    "github.com/robfig/cron/v3"
    "github.com/xuri/excelize/v2"
    "gitlab.com/mycorp/mycompany/data/datapuller/dbutil"
    "gitlab.com/mycorp/mycompany/data/datapuller/models"
    "gorm.io/gorm"
)

func main() {
...

Because the associated package needs to be pulled when building. Docker may be missing the necessary environment variables to pull these packages. It is recommended that you use the go mod vendor command,then build image

FROM  golang:1.18-alpine
ADD . /go/src/<project name>
WORKDIR /go/src/<project name>
RUN go build -mod=vendor -v -o /go/src/bin/main main.go
RUN rm -rf /go/src/<project name>
WORKDIR /go/src/bin
CMD ["/go/src/bin/main"]

When you copy your source code into the image, you only copy files in the current directory

COPY *.go ./ # just the current directory's *.go, not any subdirectories

It's usually more common to copy in the entire host source tree, maybe using a .dockerignore file to cause some of the source tree to be ignored

COPY ./ ./

Otherwise you need to copy the specific subdirectories you need into the image (each directory needs a separate COPY command)

COPY *.go ./
COPY dbutil/ dbutil/
COPY models/ models/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM