1.Docker 镜像的大小减少
1.1基本dockerfile
276MB
bash
FROM golang:1.23.1-alpine
WORKDIR /app
COPY go.* ./
RUN go mod download
COPY . .
RUN go build -o main .
CMD ["./main"]
FROM golang:1.23.1-alpine
WORKDIR /app
COPY go.* ./
RUN go mod download
COPY . .
RUN go build -o main .
CMD ["./main"]
1.2 多阶段镜像
通过使用多阶段映像,我们可以分离编译和执行阶段,这有助于从最终映像中排除不必要的文件(如 Go 构建工具)
bash
FROM golang:1.23.1-alpine AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download && go mod verify
COPY . .
RUN go build -o main .
FROM golang:1.23.1-alpine
COPY --from=builder /app /
CMD ["./main"]
FROM golang:1.23.1-alpine AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download && go mod verify
COPY . .
RUN go build -o main .
FROM golang:1.23.1-alpine
COPY --from=builder /app /
CMD ["./main"]
优化
我们优化构建阶段以生成更轻量的二进制文件
CGO_ENABLED=0:禁用对 C 库的依赖,允许我们创建静态二进制文件。
GOARCH=amd64 和 GOOS=linux:指定我们正在为 Linux amd64 架构构建。
scratch:使用临时映像,即一个不包含任何内容(没有操作系统,没有库)的空镜像,这可以通过静态二进制文件实现。
bash
FROM golang:1.23.1-alpine AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download && go mod verify
COPY . .
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -o main -a --trimpath --ldflags="-s -w" --installsuffix cgo
FROM scratch
COPY --from=builder /app /
CMD ["./main"]
FROM golang:1.23.1-alpine AS builder
WORKDIR /app
COPY go.* ./
RUN go mod download && go mod verify
COPY . .
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -o main -a --trimpath --ldflags="-s -w" --installsuffix cgo
FROM scratch
COPY --from=builder /app /
CMD ["./main"]
1.3 用UPX进行二进制压缩
对二进制进行压缩
bash
FROM golang:1.23.1-alpine AS builder
RUN apk add --no-cache upx
WORKDIR /app
COPY go.* ./
RUN go mod download && go mod verify
COPY . .
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -o main -a --trimpath --ldflags="-s -w" --installsuffix cgo
RUN upx --ultra-brute -qq main && upx --t main
FROM scratch
COPY --from=builder /app /
CMD ["./main"]
FROM golang:1.23.1-alpine AS builder
RUN apk add --no-cache upx
WORKDIR /app
COPY go.* ./
RUN go mod download && go mod verify
COPY . .
RUN CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -o main -a --trimpath --ldflags="-s -w" --installsuffix cgo
RUN upx --ultra-brute -qq main && upx --t main
FROM scratch
COPY --from=builder /app /
CMD ["./main"]