美文网首页
使用新版Golang1.18多段构建制作docker镜像的踩坑经

使用新版Golang1.18多段构建制作docker镜像的踩坑经

作者: sky_c146 | 来源:发表于2022-05-09 09:46 被阅读0次

    使用多段构建制作docker镜像时,我原先的dockerfile如下:

    FROM golang:1.18.1-alpine AS build
    
    WORKDIR /httpserver/
    
    COPY ./httpServer.go .
    
    ENV GOPROXY=https://goproxy.cn,direct \
    
        GO111MODULE=on \
    
        CGO_ENABLED=0 \
    
        GOOS=linux \
    
        GOARCH=amd64
    
    RUN go get [github.com/golang/glog](http://github.com/golang/glog) \
    
        && go build -installsuffix cgo -o ./httpserverv1.1 ./httpServer.go
    
    FROM alpine:latest
    
    COPY --from=build /httpserver/httpserverv1.1 /httpserver/httpserverv1.1
    
    RUN chmod a+x /httpserver/httpserverv1.1
    
    ENTRYPOINT ["/httpserver/httpserverv1.1"]
    

    结果构建时报错了,报错如下,看信息是拉取源码中的第三方依赖包glog报错:

    go: go.mod file not found in current directory or any parent directory.

    'go get' is no longer supported outside a module.

    To build and install a command, use 'go install' with a version,

    like 'go install example.com/cmd@latest'

    For more information, see https://golang.org/doc/go-get-install-deprecation

    or run 'go help get' or 'go help install'.

    查了相关的错误信息,说是go get已经在golang的1.17版本停用了,必须使用go install。其实这里有个坑,看官方文档如下:

    Starting in Go 1.17, installing executables with go get is deprecated. go install may be used instead.

    In Go 1.18, go get will no longer build packages; it will only be used to add, update, or remove dependencies in go.mod. Specifically, go get will always act as if the -d flag were enabled.

    httpServer.go:12:2: no required module provides package github.com/golang/glog: go.mod file not found in current directory or any parent directory; see 'go help modules'

    其实说的是go get只是不用来build了,他只能在go.mod中做依赖包相关的操作。go install是直接安装package,这里使用go install明显不对。

    掌握了了以上信息,就可以针对性的解决了。我之前的dockerfile中可以添加一下go.mod的初始化操作,新的file如下:

    FROM golang:1.18.1-alpine AS build
    
    WORKDIR /httpserver/
    
    COPY ./httpServer.go .
    
    ENV GOPROXY=https://goproxy.cn,direct \
    
        GO111MODULE=on \
    
        CGO_ENABLED=0 \
    
        GOOS=linux \
    
        GOARCH=amd64
    
    RUN go mod init httpserver \
    
        && go get [github.com/golang/glog](http://github.com/golang/glog) \
    
        && go build -installsuffix cgo -o ./httpserverv1.1 ./httpServer.go
    
    FROM alpine:latest
    
    COPY --from=build /httpserver/httpserverv1.1 /httpserver/httpserverv1.1
    
    RUN chmod a+x /httpserver/httpserverv1.1
    
    ENTRYPOINT ["/httpserver/httpserverv1.1"]
    

    问题解决,构建镜像成功了。

    相关文章

      网友评论

          本文标题:使用新版Golang1.18多段构建制作docker镜像的踩坑经

          本文链接:https://www.haomeiwen.com/subject/bwxhurtx.html