Best Practices for Go Docker Images in Production

Build Go apps in a multi-stage Dockerfile using alpine and a non-root user for secure, minimal production images.

Use a multi-stage Dockerfile with a non-root user to minimize image size and attack surface.

# Stage 1: Build
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o main .

# Stage 2: Runtime
FROM alpine:3.19
RUN apk add --no-cache ca-certificates
RUN adduser -D -g '' appuser
WORKDIR /app
COPY --from=builder /app/main .
USER appuser
CMD ["./main"]