I'm trying to build a Golang project, which contains different levels of packages inside. I've uploaded an example project here: https://github.com/David-Lor/archive.org-telegrambot/tree/example-go-dockerfile-not-building
Files
go.mod
module github.com/David-Lor/go-example
go 1.16
require github.com/gammazero/workerpool v1.1.2
Dockerfile
FROM golang:1.17.7
WORKDIR /app
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
Error
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 github.com/David-Lor/go-example/internal/foo; to add it:
go get github.com/David-Lor/go-example/internal/foo
main.go:9:2: no required module provides package github.com/David-Lor/go-example/internal/foo/bar; to add it:
go get github.com/David-Lor/go-example/internal/foo/bar
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 github.com/gammazero/workerpool v1.1.2
go: downloading github.com/gammazero/deque v0.1.0
root@e468a186536f:/data/src# /tmp/built
internal/foo
internal/foo/bar
root@e468a186536f:/data/src# go run main.go
internal/foo
internal/foo/bar
CodePudding user response:
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 ./