Dockerfile: Optimize Multi-Stage Build Layers
FROM golang:1.21-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY *.go . RUN CGO_ENABLED=0 GOOS=linux go build -o /app/my-app FROM alpine:latest COPY --from=builder /app/my-app /app/my-app EXPOSE 8080 CMD ["/app/my-app"]
This Dockerfile demonstrates an optimized multi-stage build for a Go application. It first builds the application in a Go-specific image, then copies only the compiled binary into a minimal Alpine Linux image. This signi...
The multi-stage build strategy is crucial for reducing Docker image size and improving security. In the first stage ('builder'), we use a Go image to compile the application. This stage includes all necessary build tools. The second stage starts from a minimal Alpine image. We then use `COPY --from=builder` to transfer only the compiled binary from the builder stage to the final image. This ensures that build dependencies are not included in the runtime image. The `CGO_ENABLED=0` flag and `GOOS=linux` ensure a statically linked binary, simplifying deployment. The `go mod download` step is placed before copying source code to leverage Docker's layer caching; if dependencies haven't changed, this layer is reused. The final image is lean and secure, containing only the application and its runtime requirements.
Stage 1 (Builder): Set working directory to /app Copy go.mod and go.sum Download Go modules Copy application source code Build the Go application into a binary Stage 2 (Final Image): Start from a minimal base image (e.g....