|
| 1 | +# syntax=docker/dockerfile:1 |
| 2 | + |
| 3 | +# ============================================================================== |
| 4 | +# Stage 1: Builder |
| 5 | +# Description: Compiles the Go application into a statically linked binary. |
| 6 | +# ============================================================================== |
| 7 | +FROM golang:1.21.4-alpine3.18 AS builder |
| 8 | + |
| 9 | +# Set the working directory inside the build container. |
| 10 | +WORKDIR /build |
| 11 | + |
| 12 | +# Copy dependency definition files first to leverage Docker layer caching. |
| 13 | +# This ensures 'go mod download' is only re-run if dependencies change. |
| 14 | +COPY go.mod ./ |
| 15 | + |
| 16 | +# Download dependencies. |
| 17 | +# Optimization: Use '--mount=type=cache' to persist the module cache between builds, |
| 18 | +# significantly speeding up CI/CD pipelines. |
| 19 | +RUN --mount=type=cache,target=/go/pkg/mod \ |
| 20 | + go mod download |
| 21 | + |
| 22 | +# Copy the entire source code into the container. |
| 23 | +COPY . . |
| 24 | + |
| 25 | +# Build the application binary. |
| 26 | +# Compilation Flags: |
| 27 | +# - CGO_ENABLED=0 : Ensures a statically linked binary (no dependency on C libraries). |
| 28 | +# - GOOS=linux : Explicitly targets Linux environment. |
| 29 | +# - -ldflags="-w -s": Strips debug information (DWARF) and symbol tables to reduce image size. |
| 30 | +# Optimization: Re-uses the Go build cache. |
| 31 | +RUN --mount=type=cache,target=/root/.cache/go-build \ |
| 32 | + --mount=type=cache,target=/go/pkg/mod \ |
| 33 | + CGO_ENABLED=0 GOOS=linux go build \ |
| 34 | + -ldflags="-w -s" \ |
| 35 | + -o app . |
| 36 | + |
| 37 | +# ============================================================================== |
| 38 | +# Stage 2: Runner |
| 39 | +# Description: Creates a minimal, secure production image using Distroless. |
| 40 | +# Security: Contains no shell, package manager, or unnecessary tools. |
| 41 | +# ============================================================================== |
| 42 | +FROM gcr.io/distroless/static-debian12:nonroot as release |
| 43 | + |
| 44 | +# Set the working directory to root. |
| 45 | +WORKDIR / |
| 46 | + |
| 47 | +# Retrieve the compiled binary from the builder stage. |
| 48 | +COPY --from=builder /build/app /app |
| 49 | + |
| 50 | +# Document the port that the application listens on. |
| 51 | +EXPOSE 8080 |
| 52 | + |
| 53 | +# Security Best Practice: Run as a non-root user. |
| 54 | +# Using the numeric ID 65532 (which corresponds to 'nonroot' in Distroless) |
| 55 | +# is preferred for strict Kubernetes Pod Security Standards (PSS). |
| 56 | +USER 65532:65532 |
| 57 | + |
| 58 | +# Define the immutable entrypoint for the container. |
| 59 | +ENTRYPOINT ["/app"] |
0 commit comments