2

I have this structure of my project: https://i.stack.imgur.com/SqqDh.png

And this is my Dockerfile:

FROM golang:1.19

ADD . /go/src/myapp

WORKDIR /go/src/myapp

RUN go mod init cloudmeta

RUN go get github.com/go-sql-driver/mysql
RUN go get -u github.com/gin-gonic/gin

RUN go build -o bin/cloudmeta

CMD [ "bin/cloudmeta" ]

When I trying to build my docker-container I have this error:

package cloudmeta/backend/handlers is not in GOROOT (/usr/local/go/src/cloudmeta/backend/handlers)
2
  • 1
    You shouldn't have to go mod init in your build process. Get your build working locally (outside docker), go mod init, go get ... etc. which will create go.mod & go.sum - then these files should pull in the correct dependencies in your docker build, since those files are copied along with your go source.
    – colm.anseo
    Sep 1, 2022 at 21:40
  • I suspect that your setup will work if you change the mod init to RUN go mod init cloudmeta/backend (note that I agree that this is not a good approach, but felt it was worth pointing out why it does not work).
    – Brits
    Sep 1, 2022 at 22:46

1 Answer 1

5

When building Go code in docker, you shouldn't use go mod init. Take a look at the following example dockerfile from docker docs:

# syntax=docker/dockerfile:1

FROM golang:1.16-alpine

WORKDIR /app

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

COPY *.go ./

RUN go build -o /docker-gs-ping

EXPOSE 8080

CMD [ "/docker-gs-ping" ]

The docker docs guide goes into more depth but to summarise things:

  1. You should copy your go.mod and go.sum files into your project directory in the image.
  2. Now you can run the go mod download command to install the go modules required.
  3. Then you need to copy your source code into the image.
  4. Now you can compile your source code with the go build command.
4
  • I tried this, I have that problem: failed to compute cache key: "/go.mod" not found: not found
    – Whilez
    Sep 2, 2022 at 10:12
  • @Whilez Assuming your build works outside of docker, check where your putting the go.mod file in your docker image. It could be that the file isn't where its supposed to be, if needed add some extra steps to your dockerfile that run commands that show a list of files in your directory (and/or sub directories).
    – Arran
    Sep 2, 2022 at 13:29
  • My Dockerfile is in backend dir, but Dockerfile is called in docker compose. Can that be a problem?
    – Whilez
    Sep 2, 2022 at 15:09
  • Thank you, I tried this and it works, but I need to solve the next problem :)
    – Whilez
    Sep 3, 2022 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.