Guides/Server Setup
Server Setup5 min read

How to Add Swap Space on Ubuntu

Swap space prevents your server from running out of memory and crashing. This guide covers creating a swap file, sizing it correctly, making it permanent across reboots, and tuning swappiness.

Check Current Swap and Memory

Run free -h to see current RAM and swap usage. Run swapon --show to see active swap devices. If your server has 1-2GB RAM (common on small VPS instances), Node.js builds and npm install commands regularly exhaust available memory and cause the server to kill processes. A swap file provides overflow memory at disk speed — slower than RAM but far better than crashing.

Create a Swap File

Create a 2GB swap file (fallocate is faster than dd): sudo fallocate -l 2G /swapfile. Set correct permissions: sudo chmod 600 /swapfile. Format as swap: sudo mkswap /swapfile. Enable it: sudo swapon /swapfile. Verify: free -h — you should see 2GB under Swap. The swap file is active immediately but not persistent yet.

Make Swap Persistent Across Reboots

Edit /etc/fstab and add this line: /swapfile swap swap defaults 0 0. This tells Ubuntu to mount the swap file on every boot. Test by running sudo mount -a — if no errors, the configuration is correct. Verify after reboot: swapon --show. Without this step, your swap disappears on every server restart.

Tune the Swappiness Value

Swappiness (0-100) controls how aggressively Linux uses swap. Default is 60 — Linux starts swapping when RAM is 40% full. For a server running a Node.js app, set it lower (10-20) to prefer keeping data in RAM and only use swap when necessary: sudo sysctl vm.swappiness=10. Make permanent: add vm.swappiness=10 to /etc/sysctl.conf. High swappiness causes performance degradation as the server constantly reads/writes the swap file.

Need Help?

Want this done for you?

Our engineering team handles implementations like this every week. Get a free scoping call — we will tell you exactly what it takes and what it costs.

Book a free call

© 2026 NexWorldTech — Built for Global Dominance.