main.go: no required module provides package

Viewed 5624

My Go module, stored in GitHub, successfully compiles locally; however, if I try to do it via docker, even locally in the same folder, I get an error complaining that my local package does not exist, for every local import in a subfolder:

=> ERROR [build 7/7] RUN go build -o myrepo-test .                                                                                                                                                                                                                          0.6s 
------
 > [build 7/7] RUN go build -o myrepo-test .:
#14 0.535 main.go:10:2: no required module provides package github.com/myuser/myrepo-test/common; to add it:
#14 0.535       go get github.com/myuser/myrepo-test/common
#14 0.535 main.go:13:2: no required module provides package github.com/myuser/myrepo-test/scraper/data/process; to add it:
#14 0.535       go get github.com/myuser/myrepo-test/scraper/data/process
(....)

Here is my go.mod:

module github.com/myuser/myrepo-test

go 1.16

And the docker file:

# use alpine due to its small footprint
FROM golang:1.16-buster AS build

WORKDIR /app

# download the required Go dependencies
COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY *.go ./

# FAIL
RUN go build -o myrepo-test .

##########
# Deploy #
##########

FROM gcr.io/distroless/base-debian10

WORKDIR /

COPY --from=build /myrepo-test /myrepo-test

USER nonroot:nonroot

ENTRYPOINT ["/myrepo-test"]

CMD ["/myrepo-test"]
1 Answers

#14 0.535 main.go:10:2: no required module provides package github.com/myuser/myrepo-test/common; to add it:
#14 0.535 go get github.com/myuser/myrepo-test/common

Above implies you have a package common in your source. But COPY *.go ./ won't add these folders to docker build container, it will just copy go files in current directory into docker build. As go build can't find the package common in your source in container, it will try to download it from github, so the build fails.

Then, the correct solution is as next:

Dockerfile:

FROM golang:1.16-buster AS build

WORKDIR /app

# download the required Go dependencies
COPY go.mod ./
COPY go.sum ./
RUN go mod download
#COPY *.go ./
COPY . ./

RUN ls

RUN go build -o myrepo-test .

Above will add all your sources to container including the package common etc, then build could be ok.

Related