为简单的 Golang 应用程序构建映像时,缺少 go.mod 文件

我正在按照有关为 golang Web 服务器创建 docker 应用程序的简单教程在 Windows 上使用 Docker Desktop。


给定代码:


package main


import "github.com/gin-gonic/gin"


func main() {

    r := gin.Default()

    r.GET("/ping", func(c *gin.Context) {

        c.JSON(200, gin.H{

            "message": "pong",

        })

    })

    r.Run(":3000")

}

和 Dockerfile:


FROM golang:alpine


# Set necessary environmet variables needed for our image

ENV GO111MODULE=on \

    CGO_ENABLED=0 \

    GOOS=linux \

    GOARCH=amd64


# Move to working directory /build

WORKDIR /build


# Copy and download dependency using go mod

COPY go.mod .

COPY go.sum .

RUN go mod download


# Copy the code into the container

COPY . .


# Build the application

RUN go build -o main .


# Move to /dist directory as the place for resulting binary folder

WORKDIR /dist


# Copy binary from build to main folder

RUN cp /build/main .


# Export necessary port

EXPOSE 3000


# Command to run when starting the container

CMD ["/dist/main"]

使用以下方式构建图像时:


docker build . -t go-dock

我得到:

http://img4.mukewang.com/62cb8cb5000157de08410196.jpg

为什么会这样?



炎炎设计
浏览 226回答 1
1回答

杨__羊羊

本教程跳过了使用 go 模块的步骤一种选择是删除这些行# Copy and download dependency using go modCOPY go.mod .COPY go.sum .RUN go mod download并将其替换为RUN go get -u github.com/gin-gonic/gin另一个更推荐的选项是坚持使用你需要运行的 go modules 方法go mod init然后将此行添加到您的 go.mod 文件的底部,该文件应该是从上面的命令生成的require github.com/gin-gonic/gin v1.5.0这是他的 go.mod 文件的教程示例https://github.com/afdolriski/golang-docker/blob/master/go.mod要创建 go.sum 文件,这是在您创建时创建的。go build如果您从 dockerfile 中删除此行,我相信您可以跳过创建 go.sumCOPY go.sum .
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go