@jialin.huang
FRONT-ENDBACK-ENDNETWORK, HTTPOS, COMPUTERCLOUD, AWS, Docker
To live is to risk it all Otherwise you are just an inert chunk of randomly assembled molecules drifting wherever the Universe blows you

© 2024 jialin00.com

Original content since 2022

back
RSS

Losing Fat for image — Multi-stage builds

Original Dockerfile

The original Dockerfile uses the complete golang:1.22 image as its base, resulting in a large final image (about 800-900MB) that includes the entire Go development environment, source code, and build tools.

FROM golang:1.22

WORKDIR /app

COPY go.mod go.sum ./
RUN go mod download

COPY . .

RUN go build -o main .

EXPOSE 8080

CMD ["./main"]

Better One!

The optimized version uses multi-stage builds and Alpine Linux to create a much smaller final image. Only binary and runtime essentials.

A new stage just get result from builder you mentioned.

How it goes?

Each FROM instruction: starts a new build stage. In multi-stage builds, only the stage following the first FROM instruction is entirely new. Subsequent FROM instructions begin new stages but can reference results from previous stages.

The COPY --from instruction: allows you to copy files or directories from a previous build stage or even from a completely separate Docker image. This is particularly useful in multi-stage builds for creating lean final images.

FROM golang:1.22 AS builder

WORKDIR /app

COPY go.mod go.sum ./
RUN go mod download

COPY . .

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -o main .

FROM alpine:latest  

RUN apk --no-cache add ca-certificates

WORKDIR /root/

COPY --from=builder /app/main .

CMD ["./main"]

EOF