dream989898 2018-06-06 23:17
浏览 310
已采纳

为什么我在这个多阶段构建中的最终docker镜像这么大?

After reading about the enormous image size reductions that are possible with multi-stage docker builds, I'm attempting to slim down the image size for a Dockerfile I have for building a Go binary. My Dockerfile is below.

# Configure environment and build settings.
FROM golang:alpine AS buildstage
ARG name=ddmnh
ENV GOPATH=/gopath

# Create the working directory.
WORKDIR ${GOPATH}

# Copy the repository into the image.
ADD . ${GOPATH}

# Move to GOPATH, install dependencies and build the binary.
RUN cd ${GOPATH} && go get ${name}
RUN CGO_ENABLED=0 GOOS=linux go build ${name}

# Multi-stage build, we just use plain alpine for the final image.
FROM alpine:latest

# Copy the binary from the first stage.
COPY --from=buildstage ${GOPATH}/${name} ./${name}
RUN chmod u+x ./${name}

# Expose Port 80.
EXPOSE 80

# Set the run command.
CMD ./ddmnh

The resulting image, however, doesn't seem to be size reduced at all. I suspect that the golang:alpine image is being included somehow. Below is a screenshot of the results of running docker build . on the Dockerfile above.

docker images

The alpine:latest image is only 4.15MB. Adding the size of the compiled binary (which is relatively small) I would expect no more than, say, maybe 15MB for the final image. But it's 407MB. I'm clearly doing something wrong!

How can I adjust my Dockerfile to produce an image of less size?

  • 写回答

1条回答 默认 最新

  • dongpao2871 2018-06-06 23:41
    关注

    Buried deep in the Docker documentation I found that my ARG and ENV definitions were cleared when I started the final FROM. Redefining them solved the issue:

    # Configure environment and build settings.
    FROM golang:alpine AS buildstage
    ARG name=ddmnh
    ENV GOPATH=/gopath
    
    # Create the working directory.
    WORKDIR ${GOPATH}
    
    # Copy the repository into the image.
    ADD . ${GOPATH}
    
    # Move to GOPATH, install dependencies and build the binary.
    RUN cd ${GOPATH} && go get ${name}
    RUN CGO_ENABLED=0 GOOS=linux go build ${name}
    
    # Multi-stage build, we just use plain alpine for the final image.
    FROM alpine:latest
    ARG name=ddmnh
    ENV GOPATH=/gopath
    
    # Copy the binary from the first stage.
    COPY --from=buildstage ${GOPATH}/${name} ./${name}
    RUN chmod u+x ./${name}
    
    # Expose Port 80.
    EXPOSE 80
    
    # Set the run command.
    CMD ./ddmnh
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同