Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Containerize a Next.js App With Docker

A practical guide to Dockerizing Next.js with multi-stage builds, standalone server output, static export, environment variables, deployment checks, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable production pattern is a multi-stage Docker build. For a Next.js application that performs server rendering, serves API routes, or uses other server features, set output: "standalone", build the application in one stage, and run the traced server.js in a small Node.js runtime stage as a non-root user. If every page is generated ahead of time and the site has no server-only features, use output: "export" instead and serve the generated out directory with Nginx or another static host.

This guide shows both modes, the exact build and run commands, environment-variable boundaries, production safeguards, and the failure modes that most often make a Next.js container appear broken.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the correct Next.js container mode

Make this decision before writing the Dockerfile. The output mode determines what gets built, what must run in production, and which Next.js features remain available.

Question Standalone output Static export
Next.js setting output: "standalone" output: "export"
Use it when The app needs server-side rendering, API routes, middleware, or incremental static regeneration Every route can be generated at build time and no server-only feature is required
Build result .next/standalone, plus .next/static and usually public out
Production process Node.js runs the generated server.js Nginx or another static-file server returns HTML, JavaScript, CSS, and assets
Runtime behavior Requests can execute server code Requests only read prebuilt files; API routes and server-side rendering are unavailable
Operational complexity Application process, health monitoring, and runtime configuration Static web server and cache configuration

Standalone is the safe default for a full-featured application. Static export is simpler and often cheaper to operate, but only if the application really is static. Choosing export for an app that expects API routes or request-time rendering produces a container that starts successfully while silently lacking required functionality.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

What standalone actually contains

During a standalone build, Next.js traces the files imported by the production server and places the required runtime files in .next/standalone. It is not a complete copy of your source tree. You still copy .next/static because the traced server does not automatically contain those browser assets, and you copy public when your application uses that directory.

What static export changes

With output: "export", the production artifact is the out directory. There is no Node.js application process to run after the build. Features that need a request, response, headers, cookies, or server execution must be replaced with build-time data or moved to a separate service.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prepare the project before building an image

Set the output mode in Next.js

In next.config.js (or the equivalent TypeScript configuration), choose one mode. A server-capable application uses:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "standalone",
};

module.exports = nextConfig;

A site that is entirely static uses:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "export",
};

module.exports = nextConfig;

Keep only the setting that matches the application. If your project already has a configuration object, add the property rather than replacing existing image, redirect, or experimental settings.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Keep a lockfile and a production build script

The dependency stage should be driven by package.json and the lockfile. For npm, the normal production build command is npm run build. Yarn and pnpm projects should use their own frozen-lockfile or CI install command and their corresponding build command. A missing or stale lockfile makes two image builds resolve different dependency trees, which undermines reproducibility.

Add a focused .dockerignore

Place a .dockerignore beside the Dockerfile so Docker does not upload unnecessary files to the build context:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
node_modules
.next
out
.git
.gitignore
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
*.log
.env*
Dockerfile*
docker-compose*.yml

Do not blindly exclude a file that the build needs. For example, include a checked-in custom certificate or generated schema only if your build explicitly depends on it. Excluding .env* helps prevent accidental secret upload; provide required values through the build or deployment system instead.

Build a production image with standalone output

The following Dockerfile separates dependency installation, compilation, and runtime. The 22-alpine tag is an example base image; select and periodically review a supported Node.js LTS tag appropriate for your project and security policy.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
ARG NODE_VERSION=22

FROM node:${NODE_VERSION}-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM node:${NODE_VERSION}-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NODE_ENV=production
RUN npm run build

FROM node:${NODE_VERSION}-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000

RUN addgroup --system --gid 1001 nodejs 
  && adduser --system --uid 1001 nextjs

COPY --from=builder --chown=nextjs:nodejs /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"]

If the project has no public directory, remove that COPY instruction or create the directory before building. The standalone directory must be copied to the runner’s working directory: the generated server.js expects the traced files relative to itself.

Why the stages are separate

  • deps: Copies only manifest files first, so Docker can reuse the dependency layer when application source changes without changing dependencies.
  • builder: Adds source files and compilers, then runs the Next.js production build. Development dependencies may be needed here.
  • runner: Receives only the traced runtime and static assets. It does not carry source code, package-manager caches, or the complete build toolchain.

The final process is deliberately node server.js, not npm run dev. Development mode performs file watching and is not a production server.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build and run the standalone image

  1. From the directory containing the Dockerfile, build the image:
    docker build -t nextjs-sample .
  2. Start a container and map host port 3000 to the process listening on port 3000 in the container:
    docker run --rm -p 3000:3000 nextjs-sample
  3. Open http://localhost:3000. A page response confirms that the Node.js server is reachable; test an API route and a dynamically rendered route separately if your application uses them.
  4. Stop the foreground container with Ctrl+C. In a detached deployment, use your platform’s log and health-check facilities rather than assuming that a running container means every route works.

Binding and port settings

The generated server reads the PORT environment variable, so the image sets it to 3000 and exposes that documentation port. EXPOSE does not publish a port by itself; the -p 3000:3000 option creates the host-to-container mapping. A platform may inject a different port, in which case set PORT to the platform-provided value and map traffic to that port.

Use a different package manager

For Yarn, copy yarn.lock and use the repository’s frozen install command, then run yarn build. For pnpm, enable the package manager with Corepack or use the package-manager setup required by your base image, copy pnpm-lock.yaml, perform a frozen install, and run pnpm build. The stage boundaries and runtime copy paths remain the same.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Containerize a completely static Next.js site

Choose export only when all routes and data needed by the site can be produced during the build. Set output: "export", run the build, and verify that Next.js creates out.

FROM node:22-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
ENV NODE_ENV=production
RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/out /usr/share/nginx/html
EXPOSE 80

Build and run the static image with a host port of 8080:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker build -t nextjs-static .
docker run --rm -p 8080:80 nextjs-static

Visit http://localhost:8080. The host uses port 8080 in this example while Nginx listens on port 80 inside the container. If you need clean URLs, client-side fallback routing, compression, or custom cache headers, provide an Nginx configuration that matches your routing strategy; the default server is not a substitute for testing deep links.

Static-export limitations to check before switching

  • API routes cannot run from the exported image.
  • Server-side rendering and request-time data fetching are not available.
  • Pages that depend on cookies, authorization headers, or per-request personalization need a server or a separate API.
  • Data fetched during the build becomes part of the generated artifact and requires a rebuild when the source data changes.

If any of those constraints conflicts with the application, use standalone output instead of trying to work around missing server behavior in Nginx.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle environment variables and secrets correctly

Separate values needed to compile the application from values read by the running server. Variables that are embedded into browser JavaScript or evaluated while Next.js builds must be present in the builder stage, which means changing them requires a new image build. Server-only values can generally be supplied when the container starts, provided the application reads them at runtime.

  • Never copy a real .env file into the image or leave secrets in the Docker build context.
  • Use your deployment platform’s secret mechanism for database credentials, signing keys, and private service tokens.
  • Assume values prefixed for browser exposure are public; they can be inspected by anyone who downloads the JavaScript bundle.
  • After changing a build-time value, rebuild and redeploy the image rather than only restarting the old container.

Inspect the built image and CI logs for accidental secret leakage. A secret passed as a Docker build argument can still appear in build history or intermediate layers, so use a builder’s supported secret-mount mechanism when a build truly needs private material.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Production hardening checklist

  • Pin and review the base image: Use a current Node.js LTS line approved for your project. Image tags and security patches change, so rebuild regularly and review release notes.
  • Keep the runtime small: Multi-stage copying prevents compilers, caches, and unrelated development dependencies from reaching production.
  • Run as non-root: Create a dedicated user and group, copy files with matching ownership, and keep the USER instruction in the final stage.
  • Use immutable image tags in deployment: A digest or CI-generated version tag makes rollback and auditing possible even when a human-readable tag is reused.
  • Define a health check: Probe a lightweight endpoint that your application can answer without requiring a database mutation. Configure the orchestrator to restart or remove unhealthy instances.
  • Forward logs: Write application logs to standard output and errors to standard error so the container platform can collect them.
  • Set resource limits: Memory and CPU limits prevent one container from consuming an entire host, but size them from observed workload behavior rather than a universal number.
  • Terminate gracefully: Ensure the platform sends a termination signal and allows enough shutdown time for in-flight requests.
  • Review public assets: Anything copied from public is intentionally downloadable. Do not place credentials, private exports, or internal configuration there.

Deploy the image

Next.js documents Docker as a deployment option with support for the framework’s features, and any provider that runs Docker containers can host the resulting image, including Kubernetes and cloud container services. Push the image to the registry accepted by your platform, configure its runtime environment, publish the service port, and attach persistent external services such as databases or object storage rather than writing important data into the container filesystem.

A practical CI sequence

  1. Check out the exact commit being released.
  2. Restore or create the lockfile and run the project’s tests and lint checks.
  3. Build the Docker image with a unique commit or release tag.
  4. Scan the image and dependencies according to your security policy.
  5. Push the immutable tag to the registry.
  6. Deploy that tag, inject runtime secrets, and wait for the health check to pass.
  7. Exercise a representative page, a static asset, and each critical API or server-rendered path.
  8. Keep the previous image available for rollback.

Rebuild whenever dependencies, the lockfile, Next.js configuration, source code, or build-time environment values change. A restart cannot update files that were baked into an earlier image.

Troubleshoot common failures

Symptom Likely cause Fix
Cannot find module when the container starts The runner copied an incomplete output or used a non-standalone build Set output: "standalone", rebuild, and copy .next/standalone to the runner root.
Pages load but images, JavaScript, or CSS return 404 .next/static or public was not copied Copy both directories from the builder, omitting public only when the project does not have it.
API routes return 404 in production The app was built with static export Switch to standalone and run server.js, or move the API to a separately deployed service.
The container exits immediately The command is wrong, the build artifact is missing, or the process failed during startup Run the image in the foreground, inspect logs, verify that server.js exists, and confirm the configured PORT.
Works locally but not in the image A file was ignored, a case-sensitive path differs, or a build-time variable was absent Review .dockerignore, test on a case-sensitive filesystem, and pass required build variables explicitly.
Deep links fail on the static image The static server has no history fallback for client-side routes Add the appropriate Nginx fallback configuration or use a host that supports SPA-style rewrites.
Build is unexpectedly slow Dependency layers are invalidated or the context contains large unrelated files Copy manifests before source files, keep the lockfile stable, and refine .dockerignore.
Environment changes have no effect The value was embedded during build Rebuild the image for build-time variables; provide server-only values when the container starts.

Local development: Docker or native Next.js?

Docker is useful when you need to reproduce the production image, test container networking, or align development with a containerized deployment. It is not automatically the best interactive development environment. Next.js advises considering the native development command on macOS or Windows when filesystem performance is a concern, because bind-mounted file watching can be slower through a virtualized Docker filesystem.

A common split is to run npm run dev natively for rapid editing, use a separate development container only when service parity matters, and build the production Dockerfile in CI. Whichever workflow you choose, test the same standalone or export mode that production will use before release.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Decision checklist

  • Does a request need server-rendered HTML, an API route, middleware, cookies, or incremental static regeneration? Choose standalone.
  • Can every route and data dependency be generated during npm run build, with no server process afterward? Export may be appropriate.
  • Is the lockfile copied before source code and installed in frozen or CI mode?
  • Does the standalone runner contain server.js, .next/static, and the required public files?
  • Are secrets absent from the image and supplied through the deployment environment?
  • Does the final process run as a non-root user and listen on the platform’s configured port?
  • Have you tested a direct page, a deep link, static assets, and every critical server endpoint in the built image?

For most production Next.js applications, the answer is a three-stage build ending in a non-root Node.js process running server.js. Reserve static export and Nginx for sites whose behavior is genuinely build-time and file-based; that distinction prevents the most expensive Docker deployment surprises.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.