Fix EC2 Freezing During Next.js Build

April 5, 2026

🧊 Why Your EC2 Freezes on npm run build (And How to Fix It)

You SSH into your EC2, run npm run build, and then… nothing. The instance goes silent. You wait. Then you wait some more. Eventually you give up and restart it.

Here's what's happening β€” and how to fix it permanently.

⚑ What's Going On

When you run any build command on your Next.js app:

npm run build
# or
pnpm run build
# or
bun run build

Next.js kicks off a compilation process that spikes your RAM usage β€” hard. It's compiling, bundling, optimising, tree-shaking, all at once. On a small EC2 instance (like a t2.micro or t3.small), your 1–2 GB of RAM fills up instantly.

When RAM hits 100%, Linux has nowhere to put new data. The OS panics, processes get killed, and your instance locks up completely. The only way out is a hard restart from the AWS console.


πŸ› οΈ The Fix: Create a Swap File

A swap file is disk space that acts as emergency overflow RAM.

When your actual RAM fills up, Linux quietly spills the overflow onto the swap file instead of crashing. It's slower than real RAM (it's writing to disk, after all), but your build completes instead of taking down your whole instance.

For most Next.js apps, 1–2 GB of swap is enough.

1️⃣ Check If You Already Have Swap

free -h

Look at the Swap: row. If it says 0B, you have none. Let's fix that.

2️⃣ Create the Swap File

# Create a 2GB swap file (adjust to 1G for smaller projects)
sudo fallocate -l 2G /swapfile

# Lock it down β€” only root should read this
sudo chmod 600 /swapfile

# Format it as swap space
sudo mkswap /swapfile

# Turn it on
sudo swapon /swapfile

3️⃣ Make It Permanent (Survive Reboots)

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Without this, your swap disappears every time the instance restarts.

4️⃣ Verify It Worked

free -h

You should now see something like:

              total        used        free
Mem:           1.0G        800M        200M
Swap:          2.0G          0B        2.0G

Now run your build:

npm run build

It might run a touch slower than on your local machine, but it will finish instead of freezing.


πŸ’‘ Pro Tips

πŸ“ How Much Swap Do You Need? A rough rule: match your RAM size. 1 GB RAM β†’ 1–2 GB swap. 2 GB RAM β†’ 2 GB swap. You rarely need more than 2 GB for a Next.js build.

🐌 Swap is Slow, Upgrade If Needed Swap saves you from crashes, but if your builds are consistently spilling into swap, it's a sign your instance is undersized. Consider upgrading to a t3.medium (2 vCPU, 4 GB RAM) if you're deploying frequently.

πŸ“Š Watch Memory in Real Time

# Run this in a second terminal while building
watch -n 1 free -h

You'll see your RAM fill up, then the swap kick in. Satisfying to watch.

πŸ”„ Already Frozen? Here's the Quick Restart If you're already locked out, go to AWS Console β†’ EC2 β†’ Instances β†’ Instance State β†’ Reboot. Once it's back, SSH in and set up the swap before trying the build again.