Cloud & Full Stack Engineer: Minimizing Container Footprints with Multi-Stage Dockerfiles for Next.js Standalone & Python FastAPI
Deploying a naive Dockerfile that copies the entire 1.2 GB node_modules directory for a Next.js frontend alongside an unpruned 900 MB Python FastAPI image slows down Kubernetes / Cloud Run horizontal autoscaling and expands your CVE attack surface. As a Cloud Engineer and Full Stack Engineer, I optimize production container builds using Next.js output: "standalone" file-tracing and multi-stage `uv` FastAPI builds—shrinking images by 80–85%.
1. Next.js 15 `output: "standalone"` Multi-Stage Dockerfile (Under 130 MB)
When `output: "standalone"` is enabled in `next.config.mjs`, `@vercel/nft` (Node File Trace) analyzes every server import at build time and emits a self-contained `.next/standalone` folder containing only the exact production files required to run `node server.js`:
# syntax=docker/dockerfile:1.7
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME="0.0.0.0"
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
2. Pairing Next.js Standalone with Bytecode-Compiled FastAPI Containers
For the companion Python FastAPI service, we pair a multi-stage `uv sync --frozen --no-dev` builder with `UV_COMPILE_BYTECODE=1`—identical to our hardened multi-stage Django Docker build—so both frontend and backend pods scale from zero in under 1.5 seconds on Google Cloud Run and GKE.
Need a Cloud Engineer or Full Stack Engineer to optimize your Next.js and FastAPI Docker containers? Book a 1-Day Engineering Sprint.