Sub topic 3
Naming Stages and Building a Single Target
Assume you can read a Dockerfile, run docker build, and build a small Go, Node.js, or Python application. A stage is one FROM section in a Dockerfile. Give stages names with AS so later instructions can refer to them reliably.
Name stages and select a target
FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN go build -o /out/app .
FROM scratch AS runtime
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The final image uses the runtime stage. To build only the compilation stage for debugging, run:
docker build --target build -t myapp:build .COPY --from=build copies files from the named stage without copying its compiler or source tree into the final image.
Compiled and interpreted applications
A static Go binary can run in scratch, an empty base image. This is very small, but it has no shell, certificates, or time-zone data. Add those files when the application needs them.
Node.js needs a runtime, so keep only production dependencies:
FROM node:20 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/index.js"]Python can copy a virtual environment from a build stage:
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS build
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
FROM python:3.12-slim
ENV PATH="/opt/venv/bin:$PATH"
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
COPY . .
USER nobody
CMD ["python", "app.py"]A BuildKit cache mount preserves downloaded packages between builds without adding that cache to an image layer.
Security checks
Run the final container as a non-root user with USER. Also keep credentials out of ARG, ENV, and ordinary RUN commands. Use a temporary BuildKit secret instead:
RUN --mount=type=secret,id=token \
curl -H "Authorization: Bearer $(cat /run/secrets/token)" https://example.invalidThe secret is available during that command but is not copied into the resulting layer.
Exercise
Why does --target build help debug a multi-stage Dockerfile?
Show answer
It creates an image from the named build stage, so you can inspect build tools and intermediate files without changing the production stage.