CodeBodh

Docker Multi-Stage Builds & Container Hardening for Production

Optimize Docker multi-stage builds with BuildKit cache mounts, distroless runtimes, non-root users, and SBOM attestation for lean production images.

Team CodeBodh By Team CodeBodh
Nov 24, 2026
9 min read
7 views
Docker Multi-Stage Builds & Container Hardening for Production

Executive Summary: Eliminating Bloat and Attack Surface in Production Containers

Shipping a 1.1 GB single-stage container image packed with GCC toolchains, Node.js devDependencies, package manager caches, and a root shell turns every autoscaling event into a bandwidth bottleneck and expands your CVE exposure unnecessarily. During a traffic spike, pulling bloated layers across dozens of Kubernetes nodes or cloud VMs adds 30 to 90 seconds of cold-start latency before a single health check passes.

Adopting Docker multi-stage builds with BuildKit cache mounts, minimal or distroless runtime bases, and strict non-root execution shrinks production images by 80% to 95% while stripping out compilers, package managers, and shells at runtime. This guide demonstrates how to structure deterministic multi-stage Dockerfiles for PHP 8.3 and Go services, optimize CI/CD layer caching, and enforce container hardening without slowing developer iteration.


1. Why Single-Stage Dockerfiles Fail in Production

A naive Dockerfile starts from a full OS base image such as ubuntu:24.04 or php:8.3-fpm, installs build headers (autoconf, g++, libpq-dev), runs composer install or npm run build, and ships the entire filesystem to production. Even if you append rm -rf /var/lib/apt/lists/* in a later RUN instruction, earlier immutable image layers still retain the deleted bytes on disk and in the registry.

Beyond slow image pulls and inflated registry storage, single-stage images violate defense-in-depth principles. If an attacker exploits an application vulnerability in a hardened PHP 8 web application, an image containing curl, bash, gcc, and root UID 0 gives them a complete post-exploitation toolkit inside the container.

+-----------------------------------------------------------------------+

|             Docker Multi-Stage BuildKit Pipeline Architecture         |
|---|+-----------------------------------------------------------------------+
  Local / CI Context (.dockerignore excludes .git, tests, node_modules)
                                   |
                                   v
+-----------------------------------+     +-----------------------------+
| Stage 1: deps / asset-builder     |     | BuildKit Cache Mounts       |
| - Composer / npm / Go modules     |<--->| --mount=type=cache          |
| - Compiles extensions & assets    |     | (Persists across CI runs)   |
+-----------------------------------+     +-----------------------------+
                                   |
          COPY --from=deps (Only compiled binaries & vendor/prod)
                                   |
                                   v
+-----------------------------------------------------------------------+
| Stage 2: Hardened Production Runtime (Alpine / Distroless / Scratch)  |
| - Zero compilers, zero package managers, zero shell (in distroless)   |
| - Runs as non-root USER 10001:10001 + read_only root filesystem       |
+-----------------------------------------------------------------------+
                                   |
                                   v
         OCI Registry + SBOM / Provenance Attestation + Trivy Scan

2. Structuring Deterministic Multi-Stage Dockerfiles

As detailed in the official Docker multi-stage builds documentation, every FROM ... AS <stage> instruction starts a fresh filesystem layer graph. Only artifacts explicitly transferred via COPY --from=<stage> enter the final runtime image, while build tools, temporary headers, and private build secrets remain isolated in discarded intermediate stages.

Naming your stages explicitly (for example, AS builder, AS test, and AS production) enables two high-value workflows:

  • Targeted CI Verification: Run docker build --target test . in pull-request pipelines to execute PHPUnit or Go integration tests using dev dependencies, then run docker build --target production . to emit the stripped release artifact from the exact same Dockerfile.
  • External Stage Reuse: Reference pre-built binary tools directly via COPY --from=composer:2.8 /usr/bin/composer /usr/bin/composer instead of downloading and verifying installer scripts inside your own RUN layers.

3. BuildKit Cache Mounts, Bind Mounts & Remote CI Caching

BuildKit (Docker's default builder engine) replaces sequential layer execution with a concurrent dependency graph. Rather than copying your entire repository before installing dependencies—which invalidates the dependency cache on every single commit—combine .dockerignore, manifest-first layer ordering, and BuildKit mounts as described in the Docker cache optimization guide.

  • Persistent Package Cache Mounts: Adding --mount=type=cache,target=/root/.composer/cache (or /go/pkg/mod, /root/.npm) keeps downloaded archives on the builder host across builds without baking a single byte of cache into the output image layer. For apt-get, always pass sharing=locked so parallel builds serialize lockfile access cleanly.
  • Zero-Copy Bind Mounts: When compiling a static binary, RUN --mount=type=bind,target=. exposes source files read-only during compilation without creating an intermediate COPY . . layer in the builder stage.
  • Remote Registry Cache: On ephemeral GitHub Actions or GitLab runners, pass --cache-from type=registry,ref=... and --cache-to type=registry,ref=...,mode=max so every CI job reuses intermediate builder stages instead of recompiling from scratch.
Runtime Base Image Typical Image Size Shell & Package Manager CVE Surface Best Production Use Case
Debian / Ubuntu Full 450 MB – 1.1 GB bash, apt, coreutils High (100+ packages) Builder stages only; avoid in production
Debian Slim (-slim) 80 MB – 160 MB sh, minimal apt Moderate PHP-FPM / Python apps needing glibc compatibility
Alpine Linux (musl) 18 MB – 65 MB ash, apk Low Lean PHP-FPM, Nginx, and Node.js runtimes
Google Distroless 15 MB – 30 MB None (no shell, no apt) Minimal Go, Rust, Java, and static microservices
scratch 2 MB – 12 MB None (empty filesystem) Zero OS CVEs Statically linked Go/Rust binaries (CGO_ENABLED=0)

4. Non-Root Execution, Read-Only Rootfs & Capability Dropping

By default, container processes run as uid=0(root) inside the container namespace. If a runtime kernel escape occurs—or if a host directory is bind-mounted into the container—root inside the container maps directly to root privileges on the host unless user namespaces or Docker Rootless mode are enforced.

Harden every production runtime stage with four non-negotiable controls:

  1. Explicit Non-Root UID: Create a dedicated system user with a high numeric UID (such as 10001) and set USER 10001:10001 as the final instruction so Kubernetes runAsNonRoot: true policies pass without needing username-to-UID lookups.
  2. Read-Only Root Filesystem: Run containers with --read-only (or readOnlyRootFilesystem: true in Kubernetes) and mount ephemeral tmpfs volumes only for /tmp and runtime sockets (/run).
  3. Drop All Linux Capabilities: Pass --cap-drop=ALL and --security-opt=no-new-privileges:true so processes cannot bind privileged ports below 1024 or escalate privileges via setuid binaries.
  4. Pin Base Images by SHA-256 Digest: Mutable tags like php:8.3-fpm-alpine can change silently upstream. Pin exact digests (@sha256:...) and generate SBOMs during CI builds.

5. Production Multi-Stage Dockerfiles & CI/CD Hardening Scripts

The following production Dockerfile builds a modern PHP 8.3 modular monolith using an Alpine builder stage for C extensions and Composer dependencies, then copies only compiled extensions, OPcache configs, and production vendor files into a non-root runtime stage—reducing typical image size from ~540 MB down to ~72 MB.

# syntax=docker/dockerfile:1.7

# ---- Stage 1: Compile PHP Extensions ----
FROM php:8.3-fpm-alpine3.20 AS ext-builder

RUN apk add --no-cache --virtual .build-deps 
$PHPIZE_DEPS 
postgresql-dev 
icu-dev 
linux-headers 
&& docker-php-ext-install -j$(nproc) pdo_pgsql intl opcache 
&& pecl install redis 
&& docker-php-ext-enable redis
---- Stage 2: Install Production Composer Dependencies ----
FROM composer:2.8 AS vendor-builder
WORKDIR /app

COPY composer.json composer.lock ./
RUN --mount=type=cache,target=/tmp/composer-cache 
COMPOSER_CACHE_DIR=/tmp/composer-cache 
composer install 
--no-dev 
--no-interaction 
--prefer-dist 
--optimize-autoloader 
--classmap-authoritative 
--no-scripts
---- Stage 3: Hardened Non-Root Production Runtime ----
FROM php:8.3-fpm-alpine3.20 AS production
Install only runtime shared libraries (no compilers, no -dev headers)
RUN apk add --no-cache libpq icu-libs 
&& addgroup -g 10001 -S appgroup 
&& adduser -u 10001 -S -G appgroup -H appuser
Copy compiled PHP extensions and INI configs from ext-builder
COPY --from=ext-builder /usr/local/lib/php/extensions/ /usr/local/lib/php/extensions/
COPY --from=ext-builder /usr/local/etc/php/conf.d/ /usr/local/etc/php/conf.d/

WORKDIR /var/www/html
COPY --chown=10001:10001 --from=vendor-builder /app/vendor ./vendor
COPY --chown=10001:10001 public ./public
COPY --chown=10001:10001 src ./src
COPY --chown=10001:10001 composer.json ./

USER 10001:10001
EXPOSE 9000
CMD ["php-fpm", "-F"]

For Go services—such as a custom OpenTelemetry collector sidecar or telemetry ingestion worker—you can eliminate the OS layer entirely using gcr.io/distroless/static-debian12:nonroot, producing a ~14 MB image with zero shell:

# syntax=docker/dockerfile:1.7

FROM golang:1.23-bookworm AS builder
WORKDIR /src
Download Go modules with persistent BuildKit cache
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod 
go mod download
Compile static binary using read-only bind mount (zero source copy layer)
RUN --mount=type=bind,target=. 
--mount=type=cache,target=/go/pkg/mod 
--mount=type=cache,target=/root/.cache/go-build 
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 
go build -trimpath -ldflags="-s -w" -o /out/api-worker ./cmd/worker

FROM gcr.io/distroless/static-debian12:nonroot AS production
COPY --from=builder /out/api-worker /api-worker
USER 65532:65532
ENTRYPOINT ["/api-worker"]

Finally, wire your CI/CD pipeline to build with BuildKit registry caching, attach SPDX SBOM and SLSA provenance attestations, and fail the release if critical CVEs exist before pushing to production:

#!/usr/bin/env bash
set -euo pipefail

IMAGE_REPO="ghcr.io/codebodh/api-service"
IMAGE_TAG="${GITHUB_SHA:-local}"
CACHE_REF="${IMAGE_REPO}:buildcache"
Build hardened production target with remote layer cache & SBOM attestation
docker buildx build 
--target production 
--platform linux/amd64 
--cache-from "type=registry,ref=${CACHE_REF}" 
--cache-to "type=registry,ref=${CACHE_REF},mode=max" 
--sbom=true 
--provenance=mode=max 
--tag "${IMAGE_REPO}:${IMAGE_TAG}" 
--load 
.
Verify non-root execution & read-only rootfs compatibility
CONTAINER_UID=$(docker run --rm --read-only --cap-drop=ALL "${IMAGE_REPO}:${IMAGE_TAG}" id -u)
if [[ "${CONTAINER_UID}" -eq 0 ]]; then
echo "ERROR: Container is running as root (UID 0)." >&2
exit 1
fi

echo "Verified non-root UID=${CONTAINER_UID} for ${IMAGE_REPO}:${IMAGE_TAG}"

6. Developer FAQs on Docker Multi-Stage Builds

1. How do I debug a Distroless container in production if there is no shell?

Never bake bash or curl into your production image for debugging. Instead, attach an ephemeral debug container to the running pod's process namespace using kubectl debug -it <pod> --image=busybox:1.36 --target=<container>, or build a dedicated AS debug stage in your Dockerfile using gcr.io/distroless/static-debian12:debug-nonroot for staging troubleshooting.

2. Why does my PHP-FPM container fail when I add --read-only?

PHP-FPM and Nginx write PID files, sockets, and session or cache files to /var/run, /tmp, or /var/log. Keep the container root filesystem read-only and mount writable tmpfs volumes at /tmp and /run while streaming logs to php://stderr and php://stdout rather than local disk files.

3. Can BuildKit leak private SSH keys or Composer auth tokens into image layers?

Only if you pass them via ARG, ENV, or COPY. Always use BuildKit secret mounts (RUN --mount=type=secret,id=composer_auth,dst=/root/.composer/auth.json composer install) or SSH agent forwarding (--mount=type=ssh), which expose credentials exclusively during that single RUN step without persisting them in layer history.

4. Should I use Alpine or Debian Slim for PHP and Python production images?

For Go and Rust, choose Distroless or scratch. For PHP 8.3, Alpine works cleanly and keeps images under 75 MB once C extensions are compiled in a builder stage. For Python data/ML workloads with heavy native wheels (numpy, psycopg), prefer Debian -slim to avoid musl compilation overhead and wheel compatibility gaps.


7. Summary & Production Rollout Checklist

Docker multi-stage builds turn container packaging from a security liability into a fast, deterministic release pipeline. Separating compilation stages from stripped non-root runtimes eliminates gigabytes of dead build artifacts, speeds up autoscaling pulls, and drastically reduces CVE noise across your cloud hosting infrastructure.

  1. Add a Strict .dockerignore: Exclude .git, local vendor/, node_modules/, .env files, and test fixtures from the build context.
  2. Split Builder and Runtime Stages: Move all compilers, -dev headers, and package managers into named builder stages with --mount=type=cache, copying only runtime artifacts into Alpine, Debian Slim, or Distroless.
  3. Enforce Non-Root & Read-Only Controls: Set USER 10001:10001, drop all Linux capabilities, enable --sbom=true in buildx, and gate CI merges on non-root and CVE checks.

Related Architectural & Engineering Guides

Team CodeBodh

CodeBodh Team creates high quality scripts, SaaS applications and developer tools to help you build faster.

Comments (0)

Security check against automated spam
3 × 4 = ?