首页 > 解决方案 > 为什么我在这个多阶段构建中的最终 docker 映像如此之大?

问题描述

在阅读了多阶段 docker 构建可以极大地减少图像大小之后,我试图缩小用于构建 Go 二进制文件的 Dockerfile 的图像大小。我的 Dockerfile 在下面。

# 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

然而,生成的图像似乎根本没有缩小尺寸。我怀疑该golang:alpine图像以某种方式被包含在内。下面是在docker build .上面的 Dockerfile 上运行的结果截图。

码头工人图像

alpine:latest图像只有 4.15MB 。添加已编译二进制文件的大小(相对较小),我预计最终图像的大小可能不会超过 15MB。但它是 407MB。我显然做错了什么!

如何调整我的 Dockerfile 以生成更小的图像?

标签: dockergodockerfiledocker-multi-stage-build

解决方案


深埋在 Docker 文档中,我发现当我ARG开始ENV最终的FROM. 重新定义它们解决了这个问题:

# 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

推荐阅读