![](/img/trans.png)
[英]How to build a golang docker image with go.mod in a sub folder?
[英]When building image for simple Golang Application go.mod file is missing
我按照有关为 golang Web 服务器创建 docker 应用程序的简单教程在 Windows 上使用 Docker 桌面。
鉴于代码:
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
我得到:
为什么会这样?
本教程跳过了使用 go 模块的步骤
一种选择是删除这些行
# Copy and download dependency using go mod
COPY 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.sum
COPY go.sum .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.