Luk*_*ark 7 go docker dockerfile docker-multi-stage-build
在阅读了多阶段 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
Run Code Online (Sandbox Code Playgroud)
然而,生成的图像的尺寸似乎根本没有缩小。我怀疑该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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1686 次 |
| 最近记录: |