docker - 为什么我在这个多阶段构建中的最终 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 以生成更小的图像?
解决方案
深埋在 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
推荐阅读
- javascript - 为什么图表显示值为零,但值实际上不是零?
- python - 在列表理解中分配变量
- css - 同一个动画可以有不同的过渡吗?
- matlab - 有人可以解释一下这个 Matlab 代码中的函数句柄是如何工作的吗
- flutter - 搜索用户类型功能颤动
- flutter - 在 Flutter 中单击按钮刷新 ListView.builder
- html - 如何像旧版网络聊天那样格式化自适应卡片
- macos - /usr/local/include 意外添加到我的编译命令中导致构建失败
- html - 使用 z-index 将前景元素移动到背景中的网格之前
- javascript - 有没有办法编辑 WebComponent 的 CSS/JS?