dockerfile构建方案和镜像体积优化
编译和运行环境分离
以C++项目为例,容器运行除了项目的二进制文件以外,还需要相关的依赖库,而运行环境中并不需要编译环境中的大部分依赖
# ---------- Compile ----------
FROM docker.io/library/ubuntu:latest AS builder
# Install compile related deb
RUN apt-get update && apt-get install -y --no-install-recommends \
cmake \
g++ \
libboost1.83-dev
WORKDIR /workspace
COPY . .
# Compile source code
RUN bash complie.sh
# ---------- Runtime ----------
FROM docker.io/library/ubuntu:latest
# Install runtime related deb
RUN apt-get update && apt-get install -y --no-install-recommends \
libboost-system1.83.0
# Copy bin from build image to runtime image
COPY --from=builder /workspace/project_bin /usr/local/bin/project_bin
# Environment related
RUN ldconfig -v
ENV HOME /home/ubuntu
镜像体积最小化
对于纯golang项目而言,直接生成bin文件且不需要其他依赖就可以运行,可以使用busybox镜像作为基础镜像构建
busybox基础镜像大小约2MB,一般最终的运行镜像小于10MB
# ---------- Compile ----------
FROM golang_env:latest AS builder
WORKDIR /workspace
COPY . .
# Compile source code
ARG TARGETARCH
RUN GOOS=linux GOARCH=${TARGETARCH} go build -o bin/main cmd/main.go
# ---------- Runtime ----------
FROM docker.io/library/busybox:latest
# Copy bin from build image to runtime image
COPY --from=builder /workspace/bin/main /usr/local/bin/main
# Environment relate
ENV HOME /home/ubuntu
镜像压缩
使用squash可以将整个镜像压缩成一个layer,进一步减小体积
scratch是docker中最基础也是体积最小的镜像
# ---------- Compile ----------
FROM golang_env:latest AS builder
WORKDIR /workspace
COPY . .
# Compile source code
ARG TARGETARCH
RUN GOOS=linux GOARCH=${TARGETARCH} go build -o bin/main cmd/main.go
# ---------- Squash ----------
FROM docker.io/library/busybox:latest as builder-squash
# Copy bin from build image to runtime image
COPY --from=builder /workspace/bin/main /usr/local/bin/main
# Environment relate
ENV HOME /home/ubuntu
# ---------- Runtime ----------
FROM scratch
COPY --from=builder-squash / /
浙公网安备 33010602011771号