在阅读了多阶段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
图像是以某种方式被包含的。下面是在上面的Dockerfile上运行docker build .
的结果的屏幕截图。
alpine:latest
图片仅为4.15MB。添加已编译二进制文件的大小(相对较小)我估计最终图像不会超过15MB。但它是407MB。我显然做错了什么!
如何调整我的Dockerfile以生成较小尺寸的图像?
答案 0 :(得分:2)
埋在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