Can't docker build a Golang project with internal packages


I’m trying to build a Golang project, which contains different levels of packages inside. I’ve uploaded an example project here:




go 1.16

require v1.1.2


FROM golang:1.17.7

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

COPY ./src/* ./
#RUN ls -lah # files are copied correctly; go.mod and main.go are in current directory
RUN go build -o /tmp/built


When I docker build, I got the following error on the go build command:

Step 7/7 : RUN go build -o /tmp/built
 ---> Running in 72358fb165c4
main.go:8:2: no required module provides package; to add it:
        go get
main.go:9:2: no required module provides package; to add it:
        go get
The command '/bin/sh -c go build -o /tmp/built' returned a non-zero code: 1

However, if I run the base docker image and go build or go run the app from there, it works fine (from the host system runs fine too):

$ sudo docker run -it --rm -v $(pwd):/data golang:1.17.7
root@e468a186536f:/go# cd /data/src
root@e468a186536f:/data/src# go build -o /tmp/built
go: downloading v1.1.2
go: downloading v0.1.0
root@e468a186536f:/data/src# /tmp/built
root@e468a186536f:/data/src# go run main.go


The issue is in your Dockerfile; after the operation COPY ./src/* ./ the directory structure in your image is as follows:

ZZ> docker run -it d1fae37bbfb1 /bin/sh
# cd /app
# ls -al
total 2048
drwxr-xr-x 1 root root    4096 Feb 16 19:58 .
drwxr-xr-x 1 root root    4096 Feb 16 19:59 ..
drwxr-xr-x 3 root root    4096 Feb 16 19:52 foo
-rwxr-xr-x 1 root root      97 Feb 16 19:57 go.mod
-rwxr-xr-x 1 root root     352 Feb 16 19:52 go.sum
-rwxr-xr-x 1 root root     295 Feb 16 19:52 main.go
# ls foo
bar  foo.go

So there is no internal folder which is why the build is failing.

The build will complete successfully if you change this line to:

COPY src ./

Answered By – Brits

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.