Deploy on Vexlo Cloud in 60s (₹149/mo UPI) — India's First & Only Developer PaaS. Instant INR UPI & 17 global currencies ($5/mo).
Deploy Now
Bucket 1: Docker & Node.js Fatal Errors7 min readVerified

Resolving V8 JavaScript Heap Out of Memory During Next.js Docker Builds

Fix FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory during Next.js 14/15 Docker builds. Tune NODE_OPTIONS, disable source maps, and limit SWC worker threads.

TL;DR — Immediate Production Fix

The fatal V8 crash 'FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory' occurs during next build inside Docker when the Webpack/Turbopack bundler and parallel TypeScript/SWC worker threads exceed Node.js's default old-generation heap ceiling (~1.5 GB to 2 GB inside constrained containers). Fix it permanently by (1) exporting ENV NODE_OPTIONS="--max-old-space-size=3072" inside the builder stage of your Dockerfile, (2) disabling production browser source maps and parallel webpack build workers in next.config.mjs, and (3) capping experimental.cpus to match your container's actual vCPU allocation.

Verified Root Causes in Production Environments

  • Default V8 Old-Space Ceiling vs Host Core Detection: Inside a Docker build container, os.cpus().length reads the physical host CPU count (e.g., 16 or 32 cores on a shared cloud node) and spawns dozens of parallel Next.js static generation workers, instantly exhausting a 2 GB or 4 GB container memory limit.
  • Redundant TypeScript & ESLint Checking During Docker Build: Running full AST type-checking and linting inside the constrained Docker builder stage duplicates CI checks and adds 600 MB to 1.2 GB of peak V8 heap pressure.
  • Barrel File Imports (index.ts) & Server Source Maps: Importing single icons or utilities from giant barrel packages (such as @mui/icons-material or unoptimized internal index.ts barrels) forces Webpack to parse and retain tens of thousands of modules in memory simultaneously.

1. Why Next.js Builds Crash Inside Docker While Succeeding Locally

When you run pnpm run build on a local laptop with 16 GB of unified memory, the V8 JavaScript engine dynamically expands its old-space heap up to 4 GB, and your operating system pages inactive memory blocks to fast NVMe swap. However, when the exact same commit runs inside a Docker build container on a 2 GB or 4 GB Linux VPS or CI runner, two lethal things happen simultaneously.

First, Node.js inspects cgroup memory limits and caps the V8 old-generation heap much lower—or conversely, if no cgroup build limit is passed, V8 attempts to allocate past physical RAM until the garbage collector spends 98% of CPU cycles running futile mark-sweep-compact passes. Second, Next.js queries os.cpus() to size its worker pool for static page generation. On a multi-tenant host with 16 physical cores but only 2 GB of assigned container RAM, Next.js spawns 15 worker processes that immediately collide with the V8 heap ceiling.

Dockerfile.nextjs-heap-fix
dockerfile
# syntax=docker/dockerfile:1.7
FROM node:20-alpine AS base
RUN apk add --no-cache libc6-compat
WORKDIR /app

FROM base AS deps
COPY package.json pnpm-lock.yaml ./
RUN corepack enable && pnpm install --frozen-lockfile

FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# 1. Explicitly set V8 old-space heap limit (e.g. 3072MB on a 4GB build machine)
ENV NODE_OPTIONS="--max-old-space-size=3072"
ENV NEXT_TELEMETRY_DISABLED=1
# 2. Prevent Next.js from spawning 16+ workers on shared multi-core hosts
ENV NEXT_PRIVATE_STANDALONE=true

RUN corepack enable && pnpm run build

2. Optimize next.config.mjs to Cut Peak Build RAM by 55%

Raising --max-old-space-size alone is only half the fix; if you set --max-old-space-size=4096 on a VPS that only has 2048 MB of physical RAM and no swap, the Linux kernel will immediately terminate the build with SIGKILL (Exit Code 137). To actually reduce the memory footprint of next build so it completes cleanly in under 1.5 GB of RAM, you must constrain worker concurrency and disable memory-hungry source map generation in next.config.mjs.

By setting experimental.cpus: 2 (or 1 on small 2 GB nodes), experimental.workerThreads: false, and offloading TypeScript/ESLint verification to GitHub Actions prior to the Docker build, peak Resident Set Size (RSS) drops by 45% to 60%.

next.config.mjs
javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone',
  // Disable browser & server source maps during production Docker builds
  productionBrowserSourceMaps: false,
  // Run lint and tsc in CI before docker build to save ~900MB of V8 heap
  eslint: {
    ignoreDuringBuilds: true,
  },
  typescript: {
    ignoreBuildErrors: true,
  },
  experimental: {
    // Cap worker concurrency so Next.js doesn't read host os.cpus() count
    cpus: 2,
    workerThreads: false,
    webpackMemoryOptimizations: true,
    serverSourceMaps: false,
    // Automatically tree-shake heavy barrel packages
    optimizePackageImports: [
      'lucide-react',
      '@heroicons/react',
      '@radix-ui/react-icons',
      'date-fns',
      'lodash',
    ],
  },
};

export default nextConfig;

3. Profile Heap Allocations & Configure BuildKit Swap on Ubuntu VPS

If a specific route or third-party SDK is still leaking memory during static page data collection, run next build with the --experimental-debug-memory-usage flag enabled. Next.js will print live heap snapshots after each compilation phase (compiling client, compiling server, collecting page data, and generating static pages).

On self-hosted Coolify or Ubuntu VPS instances with 2 GB to 4 GB of RAM, always configure a 4 GB NVMe swapfile and pass --memory=3500m --memory-swap=6g to your build runner so momentary V8 garbage collection spikes page smoothly to disk instead of crashing the build.

debug-nextjs-build-memory.sh
bash
# 1. Run Next.js build with live V8 heap telemetry per phase
NODE_OPTIONS="--max-old-space-size=3072 --expose-gc" \
  npx next build --experimental-debug-memory-usage

# 2. Build Docker image with explicit cgroup memory + swap allowance
docker build \
  --memory=3g \
  --memory-swap=6g \
  --build-arg NODE_OPTIONS="--max-old-space-size=2560" \
  -t vexlo-nextjs-app:latest .

Pre-Deployment Verification Checklist

  • Add ENV NODE_OPTIONS="--max-old-space-size=3072" inside the Dockerfile builder stage before RUN pnpm run build.
  • Set experimental.cpus: 2 and experimental.webpackMemoryOptimizations: true in next.config.mjs.
  • Enable optimizePackageImports for icon libraries (lucide-react, @mui/icons-material) to prevent barrel-file AST explosion.
  • Ensure the host build machine has at least 4 GB of swap space configured when building on 2 GB or 4 GB RAM instances.
India's First & Only Developer PaaS

Deploy on Vexlo Cloud in 60s (₹149/mo UPI)

Automated Docker & Nixpacks builds, managed PostgreSQL/Redis, and AI Deployment Doctor. Instant INR UPI for India or USD/EUR/GBP across 17 global currencies.

Frequently Asked Questions

What happens if I set --max-old-space-size higher than my VPS physical RAM?

If you set --max-old-space-size=4096 on a 2 GB RAM server without swap space, V8 will attempt to allocate beyond physical memory and the Linux kernel OOM killer will terminate the process with SIGKILL (Docker Exit Code 137). Always pair --max-old-space-size with a 4 GB swap file or size it to ~75% of available RAM + swap.

Why does Next.js spawn so many processes inside a small Docker container?

Until constrained via experimental.cpus in next.config.mjs, Node's os.cpus() inside a container returns the total core count of the underlying physical host server (often 16 to 64 cores) rather than your container's CPU quota.

Does enabling webpackMemoryOptimizations in Next.js 14.2+ affect production runtime performance?

No. experimental.webpackMemoryOptimizations: true only changes how Webpack caches intermediate AST and source buffers in memory during the build step; the compiled output bundle is identical.

Primary Upstream References & Specifications

Keep Debugging

Related Guides

Browse all 30 guides →