How to Set Up Swap Space on Linux VPS When RAM Is Low

One of the most common problems on small VPS instances is running out of RAM unexpectedly — especially when MySQL, Nginx, and PHP-FPM all run simultaneously. The result: the OOM Killer (Out of Memory Killer) silently terminates processes, causing your website to go down without a clear reason.

Swap Space is a portion of your SSD that Linux uses as overflow RAM. When physical memory fills up, infrequently used data gets moved to swap, keeping the system running instead of crashing. This guide walks you through the full setup on Ubuntu.

Prerequisites: Ubuntu 20.04 / 22.04 / 24.04 VPS with root or sudo access, at least 1–2 GB of free disk space.

Swap vs. RAM — What's the Difference?

RAM is fast, volatile memory the CPU reads directly. Swap is space on your storage device used as overflow memory when RAM fills up. The key difference is speed — swap on SSD is roughly 10–100× slower than RAM, but it's far better than having processes killed suddenly.

Swap doesn't solve chronic RAM shortage long-term, but it provides a safety buffer during traffic spikes or resource-intensive tasks.

Note: Some VPS providers restrict swap file creation on shared storage. Check with your provider first. AsiaGB VPS supports swap on all plans.

Recommended Swap Size

Physical RAMRecommended SwapTypical Use
512 MB – 1 GB2 GBSmall web + PHP apps
2 GB2–4 GBWordPress + MySQL
4 GB2–4 GBNode.js / Python apps
8 GB+2 GB (optional)Swap rarely needed

Avoid creating excessively large swap. SSDs have limited write cycles, and heavy swapping accelerates drive wear over time.

Step 1 — Check Existing Swap

Before creating swap, verify none exists already:

sudo swapon --show

No output means no swap is currently active. Also check available RAM and disk space:

free -h
df -h

Step 2 — Create the Swap File

Create a 2 GB swap file (adjust the size as needed):

# Create a 2 GB file (change 2G to 4G for more)
sudo fallocate -l 2G /swapfile

If fallocate isn't supported on your filesystem, use dd instead:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

Step 3 — Set Permissions and Activate

A swap file readable by all users is a security risk — lock it down first:

# Only root can read/write
sudo chmod 600 /swapfile

# Create the swap signature
sudo mkswap /swapfile

# Enable swap immediately
sudo swapon /swapfile

Confirm swap is active:

sudo swapon --show
free -h

You should see a Swap line in free -h showing the size you created.

Step 4 — Make Swap Persistent Across Reboots

Swap enabled via swapon disappears after a reboot. Add an entry to /etc/fstab to auto-mount it:

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

Verify the entry was added:

cat /etc/fstab | grep swap

Expected output: /swapfile none swap sw 0 0

Step 5 — Tune the Swappiness Value

Swappiness controls how aggressively Linux moves data to swap when RAM is still available (0–100 scale):

For a web server, set it to 10 to keep processes in RAM as long as possible:

# Check current value
cat /proc/sys/vm/swappiness

# Change temporarily (resets on reboot)
sudo sysctl vm.swappiness=10

# Make permanent
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Step 6 — Tune Cache Pressure (Optional)

vfs_cache_pressure determines how quickly Linux reclaims memory used for directory/inode caching. The default is 100; setting it to 50 helps servers cache filesystem metadata longer:

echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Monitor Swap Usage

Keep an eye on swap consumption in real-time:

# Quick overview
free -h

# Find which processes use the most swap
for file in /proc/*/status; do
  awk '/VmSwap|Name/{printf $2 " " $3 "\n"}' $file
done 2>/dev/null | sort -k2 -n -r | head -10

# Check swap statistics
vmstat -s | grep -i swap

Setting Up Swap on a Linux VPS When RAM Is Low — Full Workflow

If you want the entire process condensed into one place — from checking existing swap to enabling it permanently — the workflow below is the standard sequence that works on Ubuntu 20.04 through 24.04. It is especially useful on small VPS instances that run out of RAM when WordPress, MySQL, and Node.js run at the same time. None of these steps require a reboot, and they are safe to run on a live server:

# 1) Inspect current swap and RAM
sudo swapon --show
free -h
df -h

# 2) Create a 2 GB swap file (allocates space immediately)
sudo fallocate -l 2G /swapfile

# 3) Lock permissions so only root can read/write (avoids a security risk)
sudo chmod 600 /swapfile

# 4) Create the swap signature and enable it now
sudo mkswap /swapfile
sudo swapon /swapfile

# 5) Make it persist across reboots
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# 6) Confirm — you should see a Swap line in free -h
free -h

If fallocate is not supported on your filesystem (for example on ZFS or some container setups), switch to dd to build the file block by block, then continue from step 3 as usual. It is a little slower but works on every filesystem:

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress

Tip: If your VPS leans on swap constantly because it keeps running low on RAM, that's a signal you should upgrade the plan. Swap absorbs temporary spikes but does not make the machine faster. AsiaGB VPS starts from 500 THB/month on SSD storage and lets you scale RAM/CPU to match real-world usage.

How Much Swap Should You Set (Based on RAM)?

A common question is "how big should swap be?" The answer depends on your physical RAM and the type of workload. The rule of thumb: a VPS with little RAM should have proportionally more swap (to avoid the OOM Killer), while a VPS with plenty of RAM barely needs large swap at all. The table below is a practical guide for VPS instances running websites and databases:

Physical RAMRecommended SwapSwappinessTypical Workload
512 MB1–2 GB (2–4× RAM)10Low-traffic site + small PHP
1 GB2 GB (2× RAM)10Single WordPress site
2 GB2–4 GB (1–2× RAM)10WordPress + MySQL, multiple sites
4 GB2–4 GB (0.5–1× RAM)10Node.js / Python / e-commerce
8 GB2 GB (buffer)10Heavier apps / containers
16 GB+0–2 GB (rarely needed)1–10Database servers / RAM-bound work

These numbers are not strict rules — adjust them to your actual workload. For example, if you run MySQL with a high innodb_buffer_pool_size, keep enough free RAM and avoid heavy swapping. Conversely, a 512 MB VPS running WordPress, PHP-FPM, and MySQL together usually needs at least 2 GB of swap so processes aren't killed when several visitors hit the site at once.

Avoid oversized swap: An 8 GB swap on a 1 GB-RAM VPS doesn't improve anything — it risks making the system "appear to work" while being painfully slow, because most data lives on the SSD instead of RAM. Response times degrade until users think the site has frozen.

Tuning Swappiness and vfs_cache_pressure for Servers

Once swap exists, two values are worth tuning so your VPS uses swap intelligently: vm.swappiness and vm.vfs_cache_pressure. Both are set via sysctl and made permanent in /etc/sysctl.conf.

vm.swappiness — how eagerly Linux uses swap

This value ranges from 0 to 100; higher means Linux moves pages to swap sooner, even while RAM is still free. For a web-serving VPS, set it to 10 to keep processes in RAM as long as possible and only touch swap when memory is genuinely close to full:

# Check current value (Ubuntu default = 60)
cat /proc/sys/vm/swappiness

# Make it 10 permanently
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

vm.vfs_cache_pressure — keep metadata cache longer

The default is 100. Lowering it to 50 makes Linux retain directory/inode caches (dentry and inode cache) longer, reducing repeated disk reads, which indirectly lowers swapping. It's ideal for VPS instances with many files, such as WordPress sites with lots of plugins:

echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Verify that both values are applied:

sysctl vm.swappiness vm.vfs_cache_pressure

You should see vm.swappiness = 10 and vm.vfs_cache_pressure = 50. If the numbers are still defaults, check for duplicate lines in /etc/sysctl.conf and make sure no file under /etc/sysctl.d/ overrides them later.

Important Cautions When Using Swap on a VPS

Swap is useful but not magic. Before relying on it as a primary fix, understand these limitations:

Disabling swap safely (temporary or permanent): Disable temporarily with sudo swapoff /swapfile (re-enable with sudo swapon /swapfile). To disable permanently, also remove the line from /etc/fstab; otherwise swap will re-mount itself after the next reboot.

Remove Swap (If Needed)

To resize or remove swap entirely:

# Turn off swap first
sudo swapoff /swapfile

# Remove from fstab
sudo sed -i '/swapfile/d' /etc/fstab

# Delete the file
sudo rm /swapfile

Warning: If the swap file is heavily used, swapoff may take a long time or hang because the kernel needs to move all data back to RAM first. Only remove swap when RAM has enough free space to absorb the swapped-out data.

Full Quick-Setup Script

To configure 2 GB swap in one go, run this script:

#!/bin/bash
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
echo "✅ 2G swap created successfully"
free -h

Frequently Asked Questions (FAQ)

Does swap make a VPS faster?

No. Swap does not make the machine faster because it lives on the SSD, which is 10–100× slower than RAM. Swap's job is to "prevent crashes" when RAM fills up by temporarily holding rarely used data so processes aren't killed by the OOM Killer. If you need real speed, add RAM rather than adding swap.

How much swap should a 1 GB-RAM VPS have?

Around 2 GB (roughly 2× RAM), combined with vm.swappiness=10. That size is enough to run WordPress + MySQL + PHP-FPM on a moderately trafficked site and absorbs spikes when several visitors arrive at once without letting processes get killed.

Does swap really wear out the SSD quickly?

With low swappiness (10) and a machine that isn't swapping heavily all the time, wear is minimal and rarely a concern. But if the machine swaps in and out constantly throughout the day, it consumes SSD write cycles faster than normal — which is a sign RAM is insufficient and you should upgrade, not a fault of swap itself.

Do I need to reboot after setting up swap on a VPS?

No. Using swapon enables swap immediately without a reboot, and adding the line to /etc/fstab simply makes swap return automatically after the next reboot. There is no downtime during setup.

Run Any Workload Confidently on AsiaGB VPS

AsiaGB VPS starts from 500 THB/month on SSD storage, supporting Ubuntu 20.04–24.04 with full root access. Add swap and optimize your server immediately.

Get a VPS Now

View all affordable VPS Thailand plans →