🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Deploying Next.js: Vercel, Docker, and Self-Hosting

Next.js DevOpsđŸŸĸ Free Lesson

Deploying Next.js: Vercel, Docker, and Self-Hosting

A Next.js build is not a static folder you can drop on any file server. Depending on how you use the framework, the output may include server functions, image optimization pipelines, route handlers, and middleware that all need a compatible runtime. Deployment is therefore a decision about which of those features you rely on and where you want them executed — Vercel's managed platform, a container you operate yourself, or a hybrid where static assets live on a CDN and server code runs close to your database.

This lesson walks through the three main targets, the standalone output mode that makes containers small, how environment variables flow into each runtime, and the production checklist that prevents the classic "works locally, fails on deploy" incidents.

Prerequisites

  • !A Next.js app that builds successfully with next build
  • !Familiarity with environment variables and .env files
  • !Basic command-line and Docker knowledge for the container sections

What You'll Learn

  • 1Compare Vercel, Docker, and Node-server self-hosting trade-offs
  • 2Configure output: 'standalone' and build a slim multi-stage Docker image
  • 3Manage environment variables across local, build, and runtime scopes
  • 4Diagnose common production failures after a deploy

Pick a target before you pick tools

Each target optimizes for something different. The choice is hard to reverse once a team builds workflows around it, so make it deliberately.

TargetBest forCost profileOperational burden
VercelTeams wanting zero-ops, preview deploys, edge middlewarePer-seat plus usage; can spike with images and functionsVery low
Docker on a VM or Fly.ioRegulated data, fixed regions, predictable loadFlat per-instanceMedium: you patch and scale
KubernetesMany services, mature platform teamsCluster cost dominatesHigh
Static export onlyFully static sites with no server featuresNearly free on any CDNMinimal, but feature-limited

The feature cliff matters. output: 'export' removes the server entirely, which disables route handlers, ISR revalidation, and image optimization at runtime. If your app reads cookies on the server or exposes APIs, a static export will not run it no matter which host you choose.

Environment variables, by scope

Next.js divides environment variables into three scopes, and confusing them is one of the most common deploy failures. Variables without a NEXT_PUBLIC_ prefix are only available in server code — pages, route handlers, middleware. Anything the browser must see needs the public prefix, and the prefix means the value is inlined into the client bundle at build time, so treat it as public forever.

# .env.local — never committed, used in development
DATABASE_URL="postgresql://user:pass@localhost:5432/app"
SESSION_SECRET="dev-secret"

# .env.production.example — document required keys for the deploy pipeline
DATABASE_URL=
SESSION_SECRET=
NEXT_PUBLIC_API_BASE="https://api.example.com"

At build time on a CI runner, bake only NEXT_PUBLIC_ values in. Server secrets must be present when the server process starts, not only during the build, because serverless functions and standalone servers read them at runtime. If your Docker image builds without DATABASE_URL but the container has it at runtime, everything works — until a page is pre-rendered during the build and bakes in an error.

Standalone output for small images

The default production build copies your whole node_modules tree into the deployable artifact. Most of it is never required at runtime. Standalone mode traces the actual import graph and emits a minimal server.js plus the packages it needs:

javascript
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone',
  images: {
    remotePatterns: [
      { protocol: 'https', hostname: 'cdn.example.com' },
    ],
  },
  experimental: {
    outputFileTracingRoot: process.cwd(),
  },
};

export default nextConfig;

After next build, look under .next/standalone. Copying that directory, plus .next/static and public, into the final image typically cuts hundreds of megabytes from the artifact and speeds every cold start.

A multi-stage Dockerfile that actually works

The builder stage installs dependencies and builds; the runner stage copies only the traced output. Two steps teams forget: static assets must be copied into a .next/static path the server expects, and public must come along for user uploads and robots files.

FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM node:20-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:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
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
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
CMD ["node", "server.js"]

Running as a non-root user and pinning the Node major version are small changes that security scanners and future upgrade cycles will thank you for.

What Vercel adds when you use it

Deploying to Vercel is a git integration: every push builds, every pull request gets a preview URL, and production deploys roll out with immutable asset URLs. Image optimization, ISR, and edge middleware run on infrastructure tuned for those features, so the same next build artifacts that need careful wiring in Docker are handled for you. The trade-offs are cost at scale and less control over where server code executes and where data is stored. For many products that trade is obviously worth it; for teams with residency requirements it frequently is not.

The production checklist

Before calling a deploy done, verify the boring things. The build log should show your expected route table — static, dynamic, and API routes matching your intent. A smoke test should hit one page, one API endpoint, and one authenticated flow against the deployed URL, not localhost. Health checks should probe a lightweight route that does not touch the database, so a slow query does not cause a restart loop. And rollbacks should be one command: keep the previous image tag or Vercel deployment aliased and ready.

âš ī¸Never bake secrets into the image

Environment variables referenced during next build on CI are inlined or pre-rendered. Keep real secrets out of build args and build-time env; supply them when the container or function starts.

Production pitfalls

The post-mortems repeat: a page that reads cookies silently became dynamic and lost its CDN caching, doubling origin load on deploy day. An image domain was missing from remotePatterns, so production images 400 while local dev proxy settings hid the problem. A serverless function hit its payload or duration limit because a large PDF was generated in-request instead of queued. And the classic — npm run dev was used as the production start command somewhere in a script, so no build optimizations applied at all.

Secrets, rotation, and environment hygiene

Environment variables are the deployment's nervous system, and the discipline around them separates a smooth incident from a cascading one. Every secret should have a named owner, a rotation cadence, and a documented recovery path when the rotation breaks something. Staging should mirror production's variable names exactly, with obviously fake values, so a missing key fails the staging deploy instead of the production one. Use a secrets manager — the cloud's secret store, or a sealed secrets workflow — rather than pasting values into a CI interface where they linger in job logs. And treat the rotation itself as a deploy: announce it, run it during a quiet window, verify the old credential stops working, and keep the rollback plan visible. The teams that handle this well write a tiny smoke test that asserts every required variable is present and well-formed at boot, so a half-configured instance fails fast with a clear message instead of throwing a database error on the first user request.

Common Mistakes

Assuming .env.local values exist at runtime in production

Fix: Wire secrets through your host's runtime environment: Vercel project settings, container env vars, or a secrets manager.

Forgetting to copy .next/static and public into the standalone image

Fix: Follow the documented COPY steps exactly; missing static assets show up as unstyled pages and 404 chunks in production only.

Using output: 'export' on an app with route handlers or ISR

Fix: Use standalone output and a Node runtime, or split the static marketing pages into a separate export.

Deploying without a rollback path

Fix: Keep the previous image tag or platform deployment ready and make promotion and rollback a single scripted action.

Best Practices

  • Pin Node versions in the Dockerfile and in package.json engines so CI and production match
  • Emit a route manifest from next build in CI and diff it against expectations before promoting
  • Run smoke tests against the deployed URL on every production release
  • Separate build-time public config from runtime secrets in your variable naming scheme

Interview Questions

Q1: What does output standalone change about the build?

Next.js traces the runtime import graph and emits a self-contained server.js with only the dependencies it needs, which is what makes small Docker images possible.

Q2: Why do NEXT_PUBLIC_ variables need special care?

They are inlined into the client JavaScript at build time, so anything prefixed that way is visible to every user and cannot be rotated without a rebuild.

Q3: When is a static export sufficient?

Only for sites with no server-side features: no route handlers, no ISR, no middleware, no server-side cookie reads. Content sites and docs fit; apps generally do not.

Key Takeaways

  • Deployment targets differ in ops burden and feature access; pick one that matches your runtime needs before building workflows around it.
  • Standalone output plus a multi-stage Dockerfile produces small, fast-starting images that run as a non-root user.
  • Keep secrets at runtime and only bake NEXT_PUBLIC_ values into the build.
  • Verify the route table, smoke-test the deployed URL, and keep rollbacks one command away.
  • Most production incidents trace back to caching assumptions, missing image domains, or environment scope confusion.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement