How to Write a Dockerfile for a Go Application

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"]