How to Enable Swap on a Low-RAM VPS

You are 20 minutes into deploying a Node.js app on a 2 GB RAM VPS and suddenly the SSH session freezes, then drops. You log back in and `dmesg` shows "Out of memory: Killed process". This is the classic low-RAM VPS failure, and the fastest fix is to enable swap on that low-RAM VPS so Linux has room to breathe before it starts killing your processes. This guide walks you through creating a swap file on Ubuntu 24.04 LTS and Debian 12, sizing it correctly, making it persist across reboots, and tuning how aggressively the kernel uses it.
- Swap is not a substitute for RAM. It buys you time and prevents crashes, but heavy swapping slows disk-backed workloads down.
- A 2 GB RAM VPS should get 2 GB of swap as a starting point; more only if your workload is spiky.
- Set `vm.swappiness` to 10 so the kernel uses swap only when memory is genuinely tight.
- Create it as a file, not a partition, because you can resize or remove it without repartitioning the disk.
Prerequisites
- A Linux VPS running Ubuntu 24.04 LTS or Debian 12 with a non-root sudo user. Every command below assumes sudo.
- Root access or full sudo privileges. If you only have shell access without sudo, stop here and ask your provider for root.
- At least 1 GB of free disk space. Check with `df -h` before you start. A swap file occupies real disk space, and a full disk is its own kind of disaster.
- SSH access to the machine. You are already here, so that is settled.
Why a low-RAM VPS needs swap
Linux uses RAM for two things: running processes and caching disk I/O. When memory runs out, the kernel's out-of-memory (OOM) killer picks a process and kills it. On a low-RAM VPS with 2 GB or less, this usually happens during routine spikes, a PHP-FPM burst, a Node.js garbage collection cycle, or even `apt upgrade` running alongside your app. The result is downtime that looks like an application bug but is actually a memory problem.
Swap gives the kernel a place to park idle memory pages so it does not have to kill anything immediately. It is slower than RAM by orders of magnitude because it lives on NVMe or SSD, but on modern NVMe storage the penalty is far smaller than it was on spinning disks. For a low-RAM VPS, swap is the difference between a process that slows down briefly and a process that disappears. If you are running a Linux VPS with full root access, this is one of the first things you should configure after the OS is installed.
The common mistake is treating swap as free RAM. It is not. It is a safety net. With `vm.swappiness` tuned down, the kernel prefers RAM and only dips into swap when it has to, which is exactly the behavior you want on a small VPS.
Step 1 - Check your current memory and swap status
Before changing anything, see what you are working with. The `free` command shows both RAM and swap in human-readable form, while `swapon --show` lists active swap devices.
free -h
swapon --show
The `free` output shows a "Swap" row. If the "total" column is 0, you have no swap configured, which confirms the diagnosis. The `swapon --show` command returns nothing if no swap is active. You should also check disk space, because a swap file will consume real storage.
df -h /
Verify: the Swap row in `free -h` shows zeroes, and `swapon --show` prints no output. That is the "before" state.
Step 2 - Size the swap file correctly
There is no universal answer, but a practical rule for a low-RAM VPS is to match swap to RAM up to 4 GB, then be more conservative above that. A 2 GB RAM VPS gets a 2 GB swap file. A 1 GB RAM VPS gets 1 GB. If your workload is a database or a build server with spiky memory use, going to 1.5x RAM is reasonable. Beyond 4 GB of swap on a small VPS, you are usually masking a problem that more RAM or a different architecture would solve better.
| VPS RAM | Recommended swap | Use case |
|---|---|---|
| 1 GB | 1 - 2 GB | Nginx + PHP-FPM, small Node.js apps |
| 2 GB | 2 - 4 GB | WordPress, GitLab Runner, Redis |
| 4 GB | 2 - 4 GB | Databases, CI/CD, heavier workloads |
For a 2 GB RAM VPS, the command below creates a 2 GB file. If your VPS has less RAM, adjust the count value accordingly: 1 GB uses `count=1024`, 4 GB uses `count=4096`.
sudo fallocate -l 2G /swapfile
fallocate allocates the file instantly on modern filesystems. If it fails with "fallocate failed: Operation not supported", your filesystem does not support it. In that case use dd instead, which is slower but always works:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
Verify: the file exists and has the right size with ls -lh /swapfile. You should see a 2.0G entry. If you see a different size, the file is fragmented or the allocation failed, and you should delete it and start over.
Step 3 - Set secure permissions on the swap file
A swap file contains memory pages, which can include passwords, keys, or snippets of anything the system was processing. You do not want that readable by regular users. The standard is root-only access.
sudo chmod 600 /swapfile
chmod 600 gives the owner (root) read and write access, and nothing to anyone else. This matters more than people think, a world-readable swap file is a genuine information leak waiting to happen.
Verify: ls -l /swapfile shows `-rw-------` as the permission string.
Step 4 - Format and enable the swap file
Now you tell Linux this file is swap space, then turn it on. The mkswap command writes the swap signature, and swapon activates it.
sudo mkswap /swapfile
sudo swapon /swapfile
The output of mkswap will say "Setting up swapspace version 1" and show a UUID. That UUID is an identifier, not something you need to remember. The swapon command returns no output on success, which is the Unix way of saying "it worked".
Verify: run sudo swapon --show and you should see a row for /swapfile with a size of 2G. Also check free -h again, the Swap row should now show 2.0G total.
Step 5 - Make swap permanent across reboots
Right now swap is active, but it will not survive a reboot. To enable swap on your low-RAM VPS every time it boots, you add an entry to /etc/fstab. This file tells the system what to mount at boot, and a swap entry belongs there.
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
The format is: device path, mount point (none for swap), filesystem type (swap), options (sw), and two dump/pass values (0 0). This is the standard line for a swap file. Using tee -a appends it safely, and sudo keeps it writable only by root.
Verify: view the end of the file with cat /etc/fstab and confirm the line is there. Then test that the system can actually use it at boot:
sudo swapoff /swapfile
sudo swapon -a
The swapon -a command reads /etc/fstab and activates everything listed. If it returns without error, your fstab entry is correct. If you see an error here, fix the line before rebooting, a broken fstab can prevent the system from booting properly.
Step 6 - Tune swappiness and cache pressure
Linux has a kernel parameter called vm.swappiness that controls how aggressively it uses swap. The default on many distributions is 60, which is far too aggressive for a low-RAM VPS. At 60, the kernel starts swapping out idle memory even when RAM is available, which adds needless latency. Set it to 10 so swap is used only when memory is actually tight.
sudo sysctl vm.swappiness=10
This changes the value immediately, but it resets on reboot. To make it permanent, write it to a sysctl configuration file:
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
While you are in sysctl, consider vm.vfs_cache_pressure. This controls how much the kernel prefers to reclaim inode and dentry caches over other memory. The default of 100 is fine for most workloads, but lowering it to 50 keeps more filesystem metadata cached, which helps PHP and CMS-heavy sites that stat many files.
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.d/99-swap.conf
Verify: run sudo sysctl vm.swappiness and it should print vm.swappiness = 10. After a reboot, check again to confirm the value survived.
Step 7 - Verify swap is active and stays active
After configuring everything, do a final sweep. You want to confirm that swap is active, sized correctly, and that the swappiness value is what you set. This is also a good moment to simulate a reboot to make sure the fstab entry works, if you can afford a minute of downtime.
free -h
sudo swapon --show
cat /proc/sys/vm/swappiness
Expected output: the Swap row in free -h shows your total and 0 used. swapon --show lists /swapfile with the correct size. The cat prints 10.
If you want to test persistence without a full reboot, run sudo swapoff /swapfile && sudo swapon -a. If that succeeds, the fstab line works. On a real reboot, the system will activate the swap file automatically, and this is where the fstab entry earns its keep. If you are renting a WordPress VPS or running any memory-hungry service, this step alone prevents a whole class of mystifying crashes.
How to remove or resize swap later
Swap is not permanent in the sense that you are stuck with it. If you upgrade the VPS to more RAM and no longer need swap, or if you want to change its size, the procedure is simple. First, turn swap off. Then remove the file. Then optionally delete the fstab entry.
sudo swapoff /swapfile
sudo rm /swapfile
To fully remove it, edit /etc/fstab and delete the line containing /swapfile. Use sudo nano /etc/fstab or sudo sed -i '/swapfile/d' /etc/fstab to do it non-interactively. If you only want to resize, skip the fstab deletion, recreate the file with a new size using fallocate, then run mkswap and swapon again.
Verify: sudo swapon --show shows nothing if you removed it, or the new size if you resized it.
Troubleshooting common swap problems
"swapon failed: Invalid argument". This usually means the file was not formatted correctly with mkswap, or the filesystem does not support swap files. Run sudo mkswap /swapfile again and retry. On some filesystems like ZFS, swap files need special handling.
"fallocate failed: Operation not supported". Your filesystem does not support preallocation. Switch to the dd command shown in Step 2. It is slower but filesystem-agnostic.
Swap is active but never used. Check vm.swappiness. If it is very low or the system has plenty of free RAM, this is normal. Swap is a safety net, not a performance feature. If your workload actually needs more memory, the right fix is more RAM, not more swap. A 2GB RAM VPS plan starting around 189,000 VND per month is often a cheaper path than wrestling with constant swapping on a 1 GB box.
The system still OOMs despite swap. Check dmesg | tail -20 for OOM killer messages. If swap is active but memory is still exhausted, your workload genuinely exceeds available memory. Reduce the memory footprint of the app, or move to a VPS with more RAM. If you are running on a Linux VPS with a dedicated IPv4, a common hidden memory consumer is fail2ban or a misconfigured MySQL buffer pool.
FAQ
How much swap should I add to a low-RAM VPS?
Match swap to RAM up to 4 GB. A 2 GB VPS gets 2 GB of swap, a 1 GB VPS gets 1 GB. For database workloads, 1.5x RAM is a reasonable upper limit. Beyond 4 GB on a small VPS, add more RAM instead of more swap.
What is a good swappiness value for a VPS?
Set vm.swappiness to 10. The default of 60 causes the kernel to swap out memory even when RAM is available, which adds latency on NVMe-backed VPSes. At 10, swap is used only when memory is genuinely under pressure.
Swap file or swap partition, which is better on a VPS?
Use a swap file. It is easier to resize, remove, or recreate without repartitioning the disk, which matters on a VPS where you cannot easily manipulate partitions from outside the OS.
Why does my VPS still run out of memory with swap enabled?
Swap prevents OOM kills only if there is enough swap and the kernel has time to move pages. If your workload exceeds RAM plus swap combined, the OOM killer still fires. Check dmesg and reduce the app memory footprint or upgrade to more RAM.
Does swap wear out my NVMe SSD?
Modern NVMe drives handle swap writes without meaningful wear for typical server workloads. The kernel only swaps under pressure when swappiness is low. This is not a practical concern for a standard VPS lifespan.
Related articles
- Why my VPS runs out of RAM and how to fix it
- How to reduce memory usage on a Linux VPS
- How to optimize MariaDB on a 2 GB RAM VPS
- How to tune MySQL for a low-RAM VPS
低内存VPS增加交换分区要点
本教程介绍如何在低内存 VPS 上启用 swap 文件,以防止 OOM 杀死进程。建议将交换空间设置为与内存相当,2GB 内存配 2GB swap,并将 swappiness 调低至 10。使用 fallocate 创建文件、chmod 600 设置权限,并通过 /etc/fstab 确保重启后仍然生效。这样可以在 NVMe VPS 上以最小成本获得稳定性,适合运行 WordPress 或 Node.js 的小型服务器。


