无法在 Dockerfile 中构建 Golang。

huangapple go评论71阅读模式
英文:

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 文档中的指南提供了更详细的说明,但总结起来有以下几点:

  1. 您应该将 go.modgo.sum 文件复制到镜像中的项目目录中。
  2. 现在可以运行 go mod download 命令来安装所需的 Go 模块。
  3. 然后需要将源代码复制到镜像中。
  4. 现在可以使用 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:

  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.

huangapple
  • 本文由 发表于 2022年9月2日 04:54:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/73575310.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定