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)
CodePudding user response:
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:
- You should copy your
go.mod
andgo.sum
files into your project directory in the image. - Now you can run the
go mod download
command to install the go modules required. - Then you need to copy your source code into the image.
- Now you can compile your source code with the
go build
command.