VPS Tutorials
Next.js Build Killed on a VPS: V8 Heap, OOM and Docker Limits (2026)
Find the real build memory boundary, separate V8 failures from host or container OOM, reduce work and verify production artifacts safely.

If npm run build, pnpm build or a Docker image build suddenly prints only Killed, or reports JavaScript heap out of memory, do not immediately set NODE_OPTIONS to 8192 and keep retrying. V8 heap exhaustion, host memory exhaustion and a build-container limit are separate problems. Changing the wrong boundary can put the running website or database at risk too.
This Linux VPS guide preserves the failure evidence, identifies the effective resource limit, distinguishes the cause, adjusts the build and verifies deployment. A working next dev does not replace a successful next build.
| Failure | Start with |
|---|---|
FATAL ERROR, Reached heap limit, JavaScript heap out of memory | V8 heap use, existing Node flags and project build workload |
Only Killed or exit 137 | Kernel/container OOM evidence; also manual termination, CI cancellation and supervisors |
Docker OOM indication or increasing cgroup oom_kill | Actual build container, BuildKit or CI job resource boundary |
ENOSPC, No space left on device | Disk space/inodes, not Node heap |
| TypeScript, missing module or application prerender errors | The specific build error; memory may be unrelated |
Exit 137 commonly indicates SIGKILL, but is not an OOM-specific code. It cannot by itself identify a host limit, container limit or another termination mechanism.
In the project directory, identify the installed Next.js version:
node --version
./node_modules/.bin/next --version
./node_modules/.bin/next build --help
node -p "require('./package.json').scripts.build"
Check whether the script is just next build or also runs type checks, code generation, migrations or other tasks. Dependency installation failures are not automatically Next.js compiler failures. Keep the existing package manager and lockfile; avoid upgrading dependencies during diagnosis.
For a controlled reproduction, save logs and the real return value. This npm example needs the original build command for a pnpm project:
build_exit=0
npm run build > build-memory.log 2>&1 || build_exit=$?
tail -n 80 build-memory.log
printf 'build exit code: %s\n' "$build_exit"
Record the failure time and last stage: compilation, type checking or static generation. A successful logging pipeline such as tee must not hide a failed build. Avoid repeatedly overwriting .next in the live application's working directory.
Inspect memory, swap, disk and larger processes:
free -h
swapon --show
df -h
ps -eo pid,ppid,rss,comm --sort=-rss | head -n 20
Available memory matters more than total RAM or the used column. A 4 GB VPS running databases, applications, monitoring and other builds may have much less available. A process RSS snapshot also misses short peaks across parallel processes.
Sample during a controlled build:
vmstat 1 10
Watch subsequent swap-in/out, CPU and wait samples alongside failure logs. Brief peaks may be missed; a normal one-off free -h does not disprove pressure during compilation.
Read host kernel logs near the failure time:
sudo journalctl -k --since "20 minutes ago" --no-pager \
| grep -Ei 'out of memory|oom-kill|killed process'
Match the killed PID, process name and time to this build. Missing output cannot rule out OOM: permissions, log retention and container visibility matter. Containers generally cannot read host kernel logs directly.
For confirmed host OOM, reduce simultaneous builds and avoid database peak periods. Keep critical services running. Recurring large builds may need a larger builder or CI rather than consuming production headroom.
Free host RAM does not guarantee a container/job has capacity. For a known dedicated build container:
docker inspect build-container --format '{{json .State}}'
docker inspect build-container --format 'Memory={{.HostConfig.Memory}} MemorySwap={{.HostConfig.MemorySwap}}'
docker stats --no-stream build-container
Replace build-container with its real name/ID. OOMKilled, exit status and configured limits help, but a killed child process or deleted container may not leave a conclusive status field.
Docker memory and swap limits have separate semantics. free inside a container is not a reliable substitute for its allowance. See Docker resource constraints. Disabling the OOM killer or removing all limits can transfer the pressure to other host services.
If these readable files belong to the actual workload, record them before and after the build:
cat /proc/self/cgroup
cat /sys/fs/cgroup/memory.max
cat /sys/fs/cgroup/memory.current
cat /sys/fs/cgroup/memory.events
memory.max is this cgroup's hard limit. max means no limit at this level; ancestors can still constrain it. The oom_kill counter in memory.events records OOM kills. Use its change, timestamps and concurrent workloads, rather than attributing a historical total to this attempt. Confirm the mount/layout: reading a host-root cgroup does not automatically describe a particular builder. See cgroup v2 definitions.
The application started by docker compose up is not the builder. Changing its mem_limit may not affect RUN npm run build during docker build.
Identify the active builder:
docker buildx ls
docker buildx inspect
With the docker-container driver, BuildKit runs in a dedicated container and can have driver settings such as memory and memory-swap. Other drivers, remote builders and CI runners have their own constraints. See the Docker container driver. A healthy production container cannot prove an image build avoided OOM.
--max-old-space-size controls V8 old-generation memory in MiB. It does not cap or represent the entire Node process, child processes or build container; native modules, buffers, compilers and other processes consume memory too. See the Node.js CLI reference.
When logs specifically show JavaScript heap exhaustion and capacity permits, inspect existing NODE_OPTIONS for related flags, then try one temporary change:
NODE_OPTIONS="${NODE_OPTIONS:+$NODE_OPTIONS }--max-old-space-size=2048" npm run build
2048 is a syntax example, not a recommendation for a 2 GB VPS. Choose from the actual allowance, current heap limit, native memory and other processes. The example may even be below the current default. Resolve duplicate/conflicting heap flags first. This form affects one command and preserves the other options in the original string.
Multiple Node children can each receive their own heap allowance. A large allowance per process can exceed the combined limit. Raising V8's ceiling adds no physical RAM and can make a host/container OOM happen sooner.
Confirm Next.js version and bundler first. Current official documentation describes Turbopack as the default and --webpack as the Webpack alternative; older releases differ. Use the project's CLI help and the Turbopack documentation.
experimental.webpackMemoryOptimizations, Webpack build workers and Webpack cache recommendations apply to the Webpack path. They do not automatically fix Turbopack memory. Turbopack includes Rust code, and increasing Node heap does not expand system allowance for non-V8 allocations.
- Inspect large/duplicate dependencies and unnecessary server/client imports with tools matching the bundler.
- During static generation, avoid loading huge datasets at once; review data volume and the number of required pages.
- Check plugins adding source maps, analysis, generation or repeated compilation; remove only unnecessary work.
- Pause other builds on the runner and capture real workload measurements instead of launching simultaneous retries.
See the Next.js memory guide for tools and version constraints. Experimental diagnostics and workers can have compatibility limits: validate individually in the builder rather than combining flags from several versions.
For a confirmed Node heap issue, the official guide includes heap profiling:
node --heap-prof node_modules/next/dist/bin/next build
Profiling diagnoses memory; it does not reduce it. Calling Next CLI directly may bypass preprocessing in the original script, so preserve required steps/environment. Inspect profiles after successful completion; a forced kill may leave no complete file. Profiling and heap snapshots also cost memory/disk and are poor first actions on an already full production host.
Do not deploy ignoreBuildErrors, artifacts with required checks skipped or diagnostic-mode output as a repair. If type checking moves to a separate CI step, require its success before publication.
Check existing swap with swapon --show and the VPS, filesystem and container constraints. Swap can soften a short peak or cause prolonged paging that slows other services. Host swap does not solve a container limit when the container cannot use it.
Keep existing swap files intact and check disk space before allocating gigabytes. See VPS memory/OOM troubleshooting. If every build depends on heavy paging, expand or relocate the builder.
When runtime use is modest but build peaks are high, compile in CI or on a separate machine. Verify:
- Commit, lockfile, Node/package-manager versions and target platform agree.
- Build variables match deployment; values such as
NEXT_PUBLIC_cannot simply be replaced at runtime. - Native dependencies match the target OS/architecture; macOS output is not automatically executable on Linux.
- Complete artifacts/static resources are deployed, the previous release is retained and rollback works.
See Next.js standalone/Docker deployment. Copying only .next/standalone omits public and .next/static. Failed builds must not overwrite the working release. For a separate runner, see self-hosted GitHub Actions deployment.
Rebuild the same commit and lockfile in the real environment. Require exit 0, completion of the previously failing stage, no new related OOM events and enough peak-memory headroom for co-hosted services.
Then test pages, APIs, static assets, critical workflows and rollback. Distinguish cold builds from cached builds; one cache hit does not establish a reliable build. Retain the error, effective limits, changes and measurements. Change key variables one at a time so the result identifies what helped.