Docker Examples
A handful of Dockerfile patterns you will reach for over and over - multi-stage, distroless, healthchecks, BuildKit cache.
Docker - common patterns
EXAMPLE
# 1. Node multi-stage build FROM node:20-alpine AS deps WORKDIR /app COPY package*.json ./ RUN npm ci --omit=dev FROM node:20-alpine AS build WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM gcr.io/distroless/nodejs20-debian12 AS run WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY --from=build /app/dist ./dist USER nonroot EXPOSE 3000 CMD ['dist/server.js'] # 2. Go static binary FROM golang:1.22 AS build WORKDIR /src COPY go.* ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/app ./cmd/api FROM scratch COPY --from=build /out/app /app EXPOSE 8080 ENTRYPOINT ['/app'] # 3. Python with uv FROM python:3.12-slim AS build RUN pip install uv WORKDIR /app COPY pyproject.toml uv.lock ./ RUN uv sync --frozen --no-dev COPY . . FROM python:3.12-slim WORKDIR /app COPY --from=build /app/.venv /app/.venv COPY --from=build /app /app ENV PATH='/app/.venv/bin:$PATH' CMD ['python', '-m', 'myapp'] # 4. HEALTHCHECK HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ CMD curl -f http://localhost:3000/healthz || exit 1 # 5. BuildKit cache mount # syntax=docker/dockerfile:1.7 FROM node:20 WORKDIR /app COPY package*.json ./ RUN --mount=type=cache,target=/root/.npm npm ci COPY . . RUN npm run build
Why it matters
Multi-stage builds keep images small; distroless or scratch base images keep the attack surface tiny. Always run as non-root, always add a HEALTHCHECK, always pin the base image tag (not :latest).
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
# Common one-liners — see lesson body.
docker run --rm -it python:3-alpine python -c "print('hi')"
Try it Yourself »
Discussion
Loading…