Advanced Docker - Multi-Stage Builds, Security and CI/CD
1. Recap: From a Working Application to a Production-Ready Container
So far, this series has covered enough to develop with Docker day to day: core concepts, essential commands, efficient Dockerfiles, networking, volumes and Compose to orchestrate multiple services. This last article closes the gap between “it works in my local Compose” and “ready to run in production”: smaller images through multi-stage builds, basic and non-negotiable security, and how all of it fits into a CI/CD pipeline.
2. The Problem Multi-Stage Builds Solve
Compiling or packaging an application often requires tools the application doesn’t need at runtime: compilers, development headers, the source code itself before it’s transpiled/built. A naive Dockerfile carries all of that into the final image:
# Bad: build tools travel along to production
FROM node:20
WORKDIR /app
COPY . .
RUN npm install && npm run build
CMD ["node", "dist/server.js"]
This image includes npm, the whole node_modules (including development dependencies), the original source code and the build tools — often hundreds of MBs of dead weight that’s never used after npm run build finishes, and that also increases the image’s attack surface (more binaries, more things that can have vulnerabilities).
Multi-stage builds solve this by allowing multiple FROM blocks in the same Dockerfile, where later stages selectively copy only what they need from earlier ones — the rest of the build stage simply doesn’t exist in the final image:
# Stage 1: build, with every tool needed
FROM node:20 AS build
WORKDIR /app
COPY package*.json .
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: production, only with the build output
FROM node:20-slim
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
COPY package*.json .
CMD ["node", "dist/server.js"]
The final image contains neither the original source code nor the build tools from the first stage — only the compiled dist/ and the dependencies needed at runtime. The size reduction is usually dramatic: it’s not unusual to drop from over 1 GB to under 150 MB for the same application.
3. Multi-Stage with Compiled Languages
The gain is even more obvious with compiled languages, where the final binary needs neither the compiler nor the source code:
# Stage 1: compile the binary
FROM golang:1.22 AS build
WORKDIR /app
COPY go.mod go.sum .
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o server .
# Stage 2: just the binary, in a practically empty image
FROM scratch
COPY --from=build /app/server /server
ENTRYPOINT ["/server"]
scratch is a literally empty image — no shell, no libc, no utilities at all. A statically linked Go binary (CGO_ENABLED=0) needs none of that, resulting in a final image of just a few MBs. This is also a security advantage: an image with no shell or utilities has a drastically smaller attack surface, since there are no tools for an attacker to use even if they manage to execute something inside the container.
4. Security: Never Run as Root
By default, a container runs its processes as root, unless the base image or the Dockerfile says otherwise. This is a real risk: if a vulnerability in the application allows arbitrary code execution inside the container, that code runs as root — and although namespace isolation limits damage to the host in most cases, root inside the container still has unrestricted access to that container’s filesystem and processes, and certain container escape vulnerabilities (historically rare, but real) depend precisely on the process running as root.
The fix is to create and use an unprivileged user in the Dockerfile:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
RUN useradd --create-home appuser
COPY --chown=appuser:appuser . .
USER appuser
CMD ["python3", "app.py"]
The USER appuser instruction ensures that, from that point on, every Dockerfile command and every process in the running container runs as that user — not root. Many official images already ship with a ready-to-use non-root user (for example, node has the node user), so you just declare USER node instead of creating a new one.
5. Vulnerability Scanning
Even with good Dockerfile practices, the base image and installed dependencies can contain known vulnerabilities (CVEs) in system libraries. Scanning tools check the built image against databases of known vulnerabilities:
# Docker Scout, built into the Docker CLI
docker scout cves my-app:1.0
# Trivy, a widely used open-source alternative
trivy image my-app:1.0
The output lists packages with known vulnerabilities, their severity (low, medium, high, critical) and, when available, the version that fixes the issue — often solved just by updating the base image or a specific dependency. Running this scan as part of the CI pipeline (next) keeps an image with a known critical vulnerability from reaching production without anyone having seen the alert.
6. Docker in CI/CD Pipelines
The most common CI flow is: build the image, run tests inside it (or against it), security scan, and — only if everything passes — push to the registry and deploy. An example pipeline (GitHub Actions syntax, but the flow is the same in any CI tool):
# .github/workflows/build.yml
name: build-and-push
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build the image
run: docker build -t my-app:${{ github.sha }} .
- name: Vulnerability scan
run: docker scout cves my-app:${{ github.sha }} --exit-code --only-severity critical,high
- name: Log in to the registry
run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login registry.example.com -u user --password-stdin
- name: Push the image
run: |
docker tag my-app:${{ github.sha }} registry.example.com/my-app:${{ github.sha }}
docker push registry.example.com/my-app:${{ github.sha }}
Two practices in this pipeline are worth highlighting:
- Tag by commit SHA (
${{ github.sha }}), notlatest— every build produces an image traceable to an exact commit, essential for knowing what’s running in production and for rolling back to a previous version with confidence. --exit-codeon the scan — makes the command return a non-zero exit code if it finds a critical/high vulnerability, which stops the pipeline automatically instead of relying on someone reading the report by hand.
The build cache (Article 3 of this series) also matters in CI: ephemeral runners usually start with no local cache, so tools like docker buildx with a remote cache (--cache-from/--cache-to pointing at the registry) keep every pipeline run from rebuilding everything from scratch.
7. Series Conclusion
Over these six articles, this series went from “what is a container” to a CI/CD pipeline publishing secure, lean images: the problem Docker solves and its core concepts, everyday commands, how to write efficient Dockerfiles that take advantage of the build cache, how containers communicate over networks and persist data with volumes, how Compose orchestrates all of it locally, and finally how to take it to production with multi-stage builds, non-root containers and vulnerability scanning built into the pipeline. From here, the groundwork is laid to explore orchestration at scale (Kubernetes) and more specific infrastructure topics — but Docker on its own, used well, already covers the vast majority of everyday application development and deployment cases.
References: