A fresh nginx advisory landed recently (five memory-corruption CVEs, the worst one reachable on any listener with HTTP/2 enabled), and patching it meant rebuilding and redeploying every nginx-based image I run. That is a perfectly good moment to ask a second question: how much of what I am shipping does the container actually use?
I ran a measured slimming pass over four production images - a React SPA served by nginx, a static marketing site, an ASP.NET Core API, and this blog itself - and wrote up the Next.js pattern that composes with all of them. Nothing was changed on vibes. Every change is backed by a measurement, every candidate was smoke-tested side by side with the current image, and every deployment kept a one-command rollback. Here is what the data said and what it cost - or rather, what it saved.
- Why Image Size Still Matters
- Ground Rules
- Measure First
- React SPA: nginx Alpine to Alpine-slim
- Static Sites: Same Swap, Plus Two Classic Sins
- Next.js: Standalone Output on an Alpine Runner
- ASP.NET Core Backend: Debian to Alpine Without Breaking ICU
- This Blog: 138 MB to 51.8 MB
- The Verification Playbook
- Results Table and Deliberate Non-Changes
- Conclusion
Why Image Size Still Matters
My production runs on Linux hosts that I set up and operate myself. Images travel from the build machine the honest way: docker save, scp a tar, docker load on the server, compose up. For that topology, image size is not cosmetic - it is deploy time, and deploy time is how quickly you can ship a security fix.
Size also decides how much disk and how much registry storage your rollback inventory can keep. A 479 MB API image means you think twice about keeping yesterday’s tag around. A 302 MB one means you stop thinking.
Ground Rules
- Innocent until measured. Only change what data indicts: a layer in
docker history, a directory indu, a package inapk info. - A CVE pin is sacred. I had pinned nginx to the patched 1.31.9 for the advisories mentioned above. A slim variant is only allowed if it carries the same patched package version - verified inside both images, not assumed.
- Healthchecks are contracts. Both the compose healthchecks and the image
HEALTHCHECKexecutecurl. That 324 kB binary is part of the deployment contract, so it stays. Removing it couples an image change to a compose change, and coupling is what you are trying to avoid. - Rollback nets before anything else. Every current image got a tag like
pre-slim-2026-11-29, locally and on the production host. If a swap misbehaves, rollback is onedocker tagplusdocker compose up -d --no-build. - Candidates never touch
:latest. Slim builds are taggedslim-<date>and only become:latestafter the verification battery passes.
Measure First
For each image, the same four questions:
# 1. Two sizes - the UI number and the stored layer sum
docker images app:latest
docker image inspect -f '{{.Size}}' app:latest
# 2. What the filesystem actually holds
docker run --rm --entrypoint sh app:latest -c \
"du -sh /; du -sh /usr/share/nginx/html /usr/lib/nginx 2>/dev/null"
# 3. Layer shapes - watch for duplicate-tree layers
docker history app:latest --format '{{.Size}}\t{{.CreatedBy}}'
# 4. Contents the app can never use
docker run --rm --entrypoint sh app:latest -c \
"ls /usr/lib/nginx/modules; apk info -e; find / -xdev -name '*.map' -o -name '*.pdb' | head"
Plus a context-hygiene check most repos skip: does a .dockerignore exist? One of my four projects had no file at all - meaning a Windows node_modules tree with platform binaries could ride into a Linux build. That gets fixed first, always, because it corrupts the very measurements you are about to trust.
Two patterns to look for in docker history:
- A duplicate-tree layer: a
chown -R(orchmod -R) run after the tree wasCOPYd rewrites every file into a second layer. On the nginx images this showed up as a ~12 MB layer right after a ~12 MBCOPY- twice the content for zero reason. - Package dependencies you never load. nginx ships optional dynamic modules; if the config has no
load_moduleline, they are dead weight.
React SPA: nginx Alpine to Alpine-slim
The SPA is a pure static bundle (npm run build → dist/) served by nginx with gzip, cache headers and security headers. The measurement was brutal in its simplicity:
/usr/lib/nginxinside the image: 15.7 MB of dynamic modules -acme,geoip,njs,image-filter,xslt, each also shipped in a-debugvariant.- Shipped nginx config: zero
load_moduledirectives, zero references to any of those features.
The official image family has a variant for exactly this case: nginx:<pinned>-alpine-slim. It keeps the same nginx build of the same version, minus the optional modules and their dependency chains (no perl, no libxslt, no gd/jpeg/webp/tiff, no fontconfig).
# Production stage - pinned patched version, slim variant
# CVE-pinned 1.31.9 must survive the swap: verify, do not assume
FROM nginx:1.31.9-alpine-slim AS final
COPY --from=build /app/dist /usr/share/nginx/html
Verification that the pin held: apk info nginx printed nginx-1.31.9-r1 in both images - identical package, identical CVE fixes, fewer extras. The SPA image went from 96.4 MB to 24.7 MB. Nothing in the build output changed, so hashed asset filenames stayed identical across the swap - Cloudflare’s cache stayed valid and users kept getting cached assets.
Static Sites: Same Swap, Plus Two Classic Sins
The marketing site got the same base swap (105 MB to 35.3 MB), and two extra fixes the data had indicted:
Sin 1: post-copy chown -R
# Before: COPY writes the tree, then chown -R rewrites ALL of it as a new layer
COPY --from=build /app/dist /usr/share/nginx/html
RUN addgroup -g 1001 -S app && \
adduser -S app -u 1001 && \
chown -R app:app /usr/share/nginx/html && \
chown -R app:app /var/cache/nginx ...
# After: create the user BEFORE the copy; chown during COPY costs nothing
RUN addgroup -g 1001 -S app && adduser -S app -u 1001
COPY --from=build --chown=app:app /app/dist /usr/share/nginx/html
RUN chown app:app /var/cache/nginx /var/log/nginx /etc/nginx/conf.d && \
touch /var/run/nginx.pid && chown app:app /var/run/nginx.pid
The docker history evidence was exactly as described in the previous section: a 12.3 MB layer duplicating a 12.2 MB COPY. The rewrite turns a 12 MB content layer into two, and the duplication lives forever - in storage, in docker save tars, and in pull times.
Sin 2: no .dockerignore
The project had none. Added with the usual suspects (node_modules, dist, .env*, IDE, logs, git metadata). This does not shrink the image - it protects the build from the host filesystem sneaking into the context and from stale platform-specific binaries landing in a Linux image.
The build stage also got bumped from node:20-alpine to node:22-alpine. Build-stage bases do not affect final image size, but an end-of-life build image is a quiet liability; this one was EOL.
Next.js: Standalone Output on an Alpine Runner
Next.js deploys usually end up with a runner that carries the entire node_modules and dev dependencies because the Dockerfile naively copies the whole workdir. The framework ships the fix: standalone output copies only the server files and the traced subset of dependencies that are actually used.
# next.config.js
module.exports = { output: 'standalone' }
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-alpine AS runner # runtime stage, ~same pattern as above
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -g 1001 -S nodejs && adduser -S nextjs -u 1001
COPY --from=build --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=build --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=build --chown=nextjs:nodejs /app/public ./public
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
Two notes the official examples often skip:
- Static export instead of a server. If the site is fully static (
output: 'export'), skip the Node runner entirely and serve the export from the nginx slim variant from the React section - one base, ~25 MB, no Node process to patch. - Do not prune
.next/static. The standalone folder deliberately excludes it; copying it back is required or every chunk 404s. A missing static copy is the most common Next.js container bug I have debugged in other people’s Dockerfiles.
There is no published measurement for this app here yet - I am not going to invent numbers. The pattern above is the current recommendation for the Next.js services I maintain, and it composes with everything else in this post: same slim bases, same verification battery.
ASP.NET Core Backend: Debian to Alpine Without Breaking ICU
The API was on mcr.microsoft.com/dotnet/aspnet:10.0 (Debian) - the fattest image in the fleet at 479 MB. The candidate: aspnet:10.0-alpine. This is the swap where the data indicts and still the danger is real: Alpine images ship without ICU, and .NET silently degrades to invariant-globalization mode instead of failing. Date formatting, culture-aware comparisons, string collation - quietly different in production. That is a behavior change wearing a size-reduction costume.
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS base
WORKDIR /app
EXPOSE 8080
# ...publish stage unchanged...
FROM base AS final
# curl: compose healthcheck executes it (contract, keep)
# icu-libs: globalization parity with the former Debian base (~8 MB, buys correctness)
RUN apk add --no-cache curl icu-libs
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Api.dll"]
The musl question: libc-linked native dependencies are the classic Alpine landmine. A full audit of the published app folder found the stack to be managed-only (Npgsql, StackExchange.Redis, EF Core, JWT), and the linux/arm64 manifest for the alpine tag was verified to exist before any build was attempted.
But audit is not proof, so the swap was proven the long way: both images booted side by side against a real dependency set with a fresh restore of a production database dump, and were driven through the app’s own API - real writes through the enum CHECK constraints (the part most smoke tests never touch), background scheduler loops observed quiet with zero errors, identical healthcheck results. When one test initially failed with auth errors, the old image failed identically against the same env - a masked placeholder secret in the test harness, not a musl issue. Lesson: A/B before you blame your change.
Result: 479 MB to 302 MB (-37%), ICU installed and verified with apk info icu-libs before and after the swap, with the A/B boot showing no behavioral difference against real data.
This Blog: 138 MB to 51.8 MB
This blog is a static site served by nginx on my own Linux hosting, and it was the guinea pig. The same alpine-slim swap plus the chown fix, and nothing else - the history showed no other duplicate layers. Measured inside the image: /usr/lib/nginx 15.7 MB → 8 kB (zero modules), while the content tree stayed 11.6 MB with an identical sorted-file hash digest, so every hashed asset URL keeps working at swap time.
What made it real for my deployment style is the transfer number: the docker save tar that scp crosses the wire went from 44 MB to 17.7 MB. On a plain internet uplink, that is what patch turnaround actually feels like.
One honest quirk: on alpine-slim the apk add curl layer costs 5.6 MB instead of the 164 kB it cost on the full image, because the slim base had already dropped curl’s dependency chain and apk brings it back. The net was still -27.6 MB stored; a smaller base that re-adds a tool can still win - you just have to measure the actual sum, not the marketing number.
The Verification Playbook
Every candidate got the same battery before promotion:
- Same-patched-version proof:
apk info nginx/dotnet --versionidentical between old and new. - Content hash: a sorted
find . -type f | sort | xargs sha256sumover the app content, identical in both images. For static sites this also means CDN caches survive the swap. - Runtime facts: distro release, curl version string, non-root uid, and the
pscheck that nginx workers really run as the intended user. - A/B smoke test: both containers up at once, same request battery - key routes 200, clean-URL/deep-link fallback, 404 handling, security headers,
Cache-Controlvalues - byte-identical bodies compared by hash. - Healthcheck: container reaches
healthywith the healthcheck command untouched; zeroemerg/alert/critin the logs. - Rebuild reproducibility: the committed Dockerfile rebuilt to the exact image ID running in production.
- Rollback inventory: old tag kept on both sides, one command to go back.
Deploy followed the same script for each app, one at a time: load the new image on the Linux host, compose up with --no-build, verify locally on the host and publicly on the real domain, confirm the server repo untouched and /tmp clean.
Results Table and Deliberate Non-Changes
| Image | Change | Before | After | Delta |
|---|---|---|---|---|
| React SPA (nginx) | 1.31.9-alpine → 1.31.9-alpine-slim | 96.4 MB | 24.7 MB | -74% |
| Marketing site (nginx) | alpine-slim + node:22 + COPY --chown + .dockerignore | 105 MB | 35.3 MB | -66% |
| ASP.NET API | aspnet:10.0 → aspnet:10.0-alpine + icu-libs, curl | 479 MB | 302 MB | -37% |
| This blog (nginx) | alpine-slim + COPY --chown | 138 MB | 51.8 MB | -62% |
| … same image, shipped tar | — | 44.0 MB | 17.7 MB | -60% |
Deliberately left alone, and why:
curland the healthcheck command - deployment contract, see ground rules.- The .NET SDK build stage base - it never ships in the final image, so it is a hygiene concern, not a size one.
- Image digests for build-stage tracing - no caching change was proven, no caching flag added.
chiseledvariants - tempting for the .NET runtime, but they are Ubuntu Pro-licensed for production support, and my verification was already green on alpine; two variables at once is how you lose an evening.
Conclusion
Across a React SPA, a marketing site, an ASP.NET API, and this blog, four shipped images lost between 37% and 74% of their size, every one of them without a single byte of changed application content - and all of it in the same week the nginx advisory forced a fleet-wide rebuild anyway. The two highest-value moves were embarrassingly cheap: use the -alpine-slim variant of a base image your app already uses, and stop duplicating trees with post-copy chown -R. The one move that needed real care was the .NET Debian-to-alpine swap, and ICU plus an A/B test against real production data is what makes it safe.
Measure first, prove the pins survive, smoke-test old against new, and keep the rollback tag. The images shrink, the patch turnarounds drop, and nothing surprises you at 3 a.m.
💬 Comments & Reactions