Skip to content

Dockerfiles

Multi-stage builds with language-specific builders and minimal production images.

Build environments carry compilers, toolchains, and cached dependencies that don’t belong in a production image. Keep the two stages separate and copy only what the process needs to run.

Go

FROM golang:1.26-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /server ./cmd/server

FROM gcr.io/distroless/static-debian13
COPY --from=builder /server /server
USER nonroot:nonroot
ENTRYPOINT ["/server"]

CGO_ENABLED=0 produces a static binary with no libc dependency, so the final image needs nothing beyond the binary itself. distroless/static is ~2 MB and includes only a non-root user and CA certificates.

Rust

FROM rust:1.96-slim AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
# Cargo refuses to build a manifest without sources; a stub main lets the
# dependency compilation cache as its own layer.
RUN mkdir src && echo 'fn main() {}' > src/main.rs \
    && cargo build --release --locked \
    && rm -rf src
COPY src ./src
# touch forces a rebuild of the crate itself; the copied files can carry
# timestamps older than the stub artifacts, which would make cargo skip it.
RUN touch src/main.rs && cargo build --release --locked

FROM gcr.io/distroless/cc-debian13
COPY --from=builder /app/target/release/server /server
USER nonroot:nonroot
ENTRYPOINT ["/server"]

The stub build compiles every dependency into a cached layer, so source changes only recompile the crate itself. The final image uses distroless/cc because the default Rust target links against glibc dynamically. To use distroless/static instead, build for x86_64-unknown-linux-musl.

TypeScript / Node

FROM node:26-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:26-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist
USER node
ENTRYPOINT ["node", "dist/index.js"]

The final stage reinstalls with --omit=dev rather than copying node_modules from the builder. This keeps devDependencies out of the image. The node user is pre-created in all official Node images.

Final image choices

Image Size Use when
gcr.io/distroless/static-debian13 ~2 MB Static binary (Go, Rust + musl)
gcr.io/distroless/cc-debian13 ~20 MB Binary that links glibc (default Rust)
alpine ~7 MB Needs a shell or apk packages at runtime
debian:trixie-slim ~75 MB Needs full glibc compatibility or apt packages

Distroless images contain no shell or package manager, leaving nothing for an attacker to exec into if the container is compromised.

Type to search…

↑↓ navigate↵ selectEsc close