英文:
Can't build Golang in dockerfile
问题
我有这个项目的结构:
https://i.stack.imgur.com/SqqDh.png
这是我的 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" ]
当我尝试构建我的 Docker 容器时,出现了以下错误:
package cloudmeta/backend/handlers is not in GOROOT (/usr/local/go/src/cloudmeta/backend/handlers)
英文:
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)
答案1
得分: 5
在使用 Docker 构建 Go 代码时,不应使用 go mod init
。请参考 Docker 文档中的以下示例 Dockerfile:
# 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"]
Docker 文档中的指南提供了更详细的说明,但总结起来有以下几点:
- 您应该将
go.mod
和go.sum
文件复制到镜像中的项目目录中。 - 现在可以运行
go mod download
命令来安装所需的 Go 模块。 - 然后需要将源代码复制到镜像中。
- 现在可以使用
go build
命令编译源代码。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论