Write a multi-stage Dockerfile to build your Go app in a builder image and copy the binary to a minimal runtime image.
Use a multi-stage Dockerfile to compile your Go application in a builder stage and copy only the binary to a minimal runtime stage. This reduces image size and attack surface by excluding the Go toolchain and source code from the final container.
# Stage 1: Build
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN go build -o main .
# Stage 2: Runtime
FROM alpine:latest
WORKDIR /root/
COPY --from=builder /app/main .
CMD ["./main"]
A Dockerfile is a recipe that tells Docker how to package your Go code into a portable container. Using a multi-stage build is like cooking a meal in a large kitchen and then serving only the finished dish, leaving the heavy equipment and raw ingredients behind. This keeps your final container small, fast, and secure.