Go程序打包成Docker镜像体积优化

Go程序打包成Docker镜像体积优化

基于Golang官方镜像进行打包时的体积较大

Dockerfile文件内容

FROM golang:1.16.5  
WORKDIR /alert   # Golang官方镜像默认工作目录为/src,强烈建议先自定义工作目录
ENV GOPROXY="https://goproxy.cn,direct"
COPY go.mod go.sum main.go ./
COPY config config/
RUN cd config/ && go mod tidy
COPY message message/
RUN cd /alert
RUN go build
COPY ./config/config.yaml .
EXPOSE 13344
CMD ["./alert","./config.yaml"]

打包并查看镜像大小

]# docker build . -t alert:from-golang --no-cache
]# docker image ls alert:from-golang 
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
alert               from-golang         599e2c1cd10b        10 seconds ago      872MB

使用多级构建方式进行打包

FROM golang:latest
WORKDIR /alert
ENV GOPROXY="https://goproxy.cn,direct"
COPY go.mod go.sum main.go ./
COPY config config/
RUN cd config/ && go mod tidy
COPY message message/
RUN cd /alert
RUN go build

FROM ubuntu 
COPY --from=0 /alert/alert .
COPY ./config/config.yaml .
EXPOSE 13344
CMD ["./alert","./config.yaml"]

打包并查看镜像大小

]# docker build . -t alert:from-ubuntu --no-cache
]# docker image ls alert:from-ubuntu 
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
alert               from-ubuntu         a912cc9bcd24        16 seconds ago      80.5MB

可以看到镜像体积缩小很多。

Go程序打包成Docker镜像体积优化

上一篇:EF 增删改查


下一篇:Lc面试题0109字符串轮转