How to configure swap on Linux Ubuntu: when you need it and how to size it

Learn how to configure swap on Linux Ubuntu as a buffer for low-RAM VPS. See when you need it, how to size the swapfile and tune swappiness for production.

A VPS with 1 or 2 GB of RAM frequently runs into situations where an npm build, a heavy PostgreSQL query or a traffic spike pushes memory to the limit. Without swap configured, the Linux kernel triggers the OOM killer and kills whichever process is consuming the most — usually the service you most need running. With swap, the system has a buffer to absorb sporadic spikes before reaching that extreme.

Swap is not magic and does not replace RAM. When the kernel starts paging actively, performance degrades brutally — reading swap on NVMe SSD is still hundreds of times slower than RAM. But as a safety net, swap prevents crashes that would ruin server uptime because of a momentary exception.

This tutorial covers the complete flow: identifying whether your VPS needs swap, creating and activating a properly sized swapfile, tuning swappiness for server workloads, and removing or resizing if necessary. Target audience: Linux sysadmins managing Ubuntu 22.04 or 24.04 on low-RAM VPS. Execution time: 10-15 minutes.

Prerequisites

Prerequisites

Ubuntu 22.04 LTS or 24.04 LTS with sudo access, an active SSH session and at least 2 GB free on disk (for a 2 GB swapfile with headroom). You also need to know the VPS’s current RAM — free -h shows it.

Before creating swap, confirm the machine’s current memory and swap state. Modern VPS often already come with swap configured by the provider or the base image — checking beforehand avoids creating duplicate swap.

Minimum recommended RAM 1 GB
Ubuntu cloud default swap 0 (none)
Swapfile path /swapfile
Swapfile permission 600 (root only)

When to create swap on your VPS

Not every VPS needs swap. The decision depends on the available RAM and the workload profile. For servers with 8 GB+ of RAM running properly sized applications, swap is rarely touched and can even get in the way (see the swappiness section).

Scenarios where swap makes sense:

  • VPS with 1-4 GB of RAM running a web stack (nginx + PHP-FPM + MySQL/Postgres)
  • Server that runs sporadic builds (npm install, composer install, docker build) consuming RAM above steady-state
  • Applications with unpredictable spikes (large file import, image processing, report generation)
  • Small databases running alongside the app on the same VPS without cgroups isolating resources

Scenarios where swap does not help:

  • Application that needs constant RAM above what is available — add RAM or upgrade the VPS
  • Latency-sensitive server (gateway, high-QPS reverse proxy) where any swap kills p99
  • Large production database — configure cgroups and swappiness=1 or disable swap entirely to avoid unpredictable I/O latency
01

Check current RAM and swap:

free -h

Typical output for a VPS without swap:

               total        used        free      shared  buff/cache   available
Mem:           1.9Gi       420Mi       180Mi       2.0Mi       1.3Gi       1.4Gi
Swap:             0B          0B          0B

If the Swap line shows nonzero values, swap already exists — skip to the “Tuning swappiness” section.

02

Check free disk space before allocating the swapfile:

df -h /

Confirm that / has at least 3-4 GB free. The swapfile will consume the allocated size in full — it is not a sparse file.

Creating the swapfile

We are going to create a 2 GB swapfile at /swapfile. This size covers the vast majority of cases for VPS with 2-4 GB of RAM. If your VPS has only 1 GB of RAM, adjust to 1 GB. For 4 GB+ of RAM, 2 GB of swap remains sufficient — do not scale linearly.

01

Allocate the file with fallocate:

sudo fallocate -l 2G /swapfile

fallocate reserves the space instantly without zeroing block by block (unlike dd, which would take minutes). On modern filesystems (ext4, xfs), it works without issues.

02

Restrict file permissions:

sudo chmod 600 /swapfile

Swap contains process memory content — including passwords, tokens and sensitive data that were in RAM. Leaving it readable by other users is a serious security flaw.

03

Format the file as a swap area:

sudo mkswap /swapfile

Expected output:

Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=abc123...
04

Activate swap:

sudo swapon /swapfile

No output on success. Confirm with:

sudo swapon --show
free -h

The Swap line in free -h now shows 2.0Gi total.

Persistence across reboot

The swapon command activates swap immediately, but the configuration does not survive reboot. Without editing /etc/fstab (next step), you lose swap every time the VPS restarts.

05

Add swap to /etc/fstab to mount automatically at boot:

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

Review the file:

sudo cat /etc/fstab

The last line should be exactly /swapfile none swap sw 0 0.

Be careful editing fstab

A syntax error in /etc/fstab prevents the VPS from booting — you would need access to the provider’s serial console to recover. Use sudo tee -a (append) instead of an editor to avoid accidentally overwriting the entire file.

Tuning swappiness for server workloads

Swappiness controls how aggressively the kernel will page memory to swap. Values range from 0 (avoid swap as much as possible) to 100 (page as soon as possible). Ubuntu’s default is 60, optimized for desktop where swap frees RAM for disk cache that improves UX. On a server, this behavior is counterproductive — you want apps to run in real RAM, even at the cost of a little cache.

01

Check the current value:

cat /proc/sys/vm/swappiness

Most Ubuntu installations return 60.

02

Temporarily reduce it to 10 (until the next reboot):

sudo sysctl vm.swappiness=10

Output:

vm.swappiness = 10
03

Persist the change in /etc/sysctl.conf so it survives reboot:

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

Check the configuration after the next boot by running cat /proc/sys/vm/swappiness — it should show 10.

Swappiness for databases

On a VPS running PostgreSQL, MySQL or MongoDB as the main service, consider swappiness=1. Databases manage their own buffer pool in RAM and lose performance brutally when the kernel decides to page hot pages. A value of 0 is even more aggressive but can cause OOM during spikes — 1 is the practical balance.

Verification

Confirm that swap is active, sized correctly and configured to persist.

01

Complete memory and swap state:

free -h
swapon --show
cat /proc/sys/vm/swappiness

You should see 2 GB of swap active, priority -2 (default), and swappiness=10.

02

Check that it will mount at boot:

grep swapfile /etc/fstab

Expected line: /swapfile none swap sw 0 0.

03

Monitor real usage under load. Use vmstat to see swap activity:

vmstat 1 5

Focus on the si (swap in, KB/s read from swap) and so (swap out, KB/s written to swap) columns. On a healthy VPS, both stay at 0 most of the time. Occasional activity during spikes is normal. Constant activity of hundreds of KB/s indicates a real RAM shortage.

Troubleshooting

”swapon: /swapfile: insecure permissions 0644”

File permissions are too open. Fix with sudo chmod 600 /swapfile and try to activate again. Common error if you used dd instead of fallocate without adjusting permission afterwards.

”fallocate: fallocate failed: Operation not supported”

Some VPS use older filesystems or layered filesystems (overlay in Docker, for example) that do not support fallocate. Replace with the classic method using dd:

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

Takes 30-60s on SSD. Then continue normally with chmod, mkswap and swapon.

Swap active but free -h still shows 0B

Confirm that the swapfile was formatted with mkswap before swapon. If you skipped the formatting step, swapon fails silently on some kernels. Run sudo swapoff /swapfile, sudo mkswap /swapfile, sudo swapon /swapfile.

System slow after enabling swap

Most likely swappiness is high and the kernel is paging hot pages. Reduce it to 10 as in the previous section. If the system remains slow even with low swappiness and vmstat shows constant si/so, RAM is genuinely insufficient — consider upgrading the VPS.

Next steps

With swap configured, the server gains resilience against sporadic memory spikes. Next points to round out the foundation of a production VPS:

  • Configure per-service memory limits with systemd (MemoryMax= in unit files) to prevent one process from taking down others
  • Continuously monitor swap usage via Netdata, Grafana or your own system — alert when si/so crosses a threshold
  • On a VPS running containers, configure --memory and --memory-swap in Docker to isolate workloads
  • Evaluate whether the application has a real memory leak — swap masks the symptom but does not fix the cause
  • If you are putting this into production, a Hostini VPS comes with fast NVMe (low swap latency when needed) and transparent RAM sizing, avoiding most scenarios where swap saves the server.

Frequently asked questions

Does swap replace RAM on production servers?

No. Swap is storage (SSD/NVMe) used as a memory extension — orders of magnitude slower than real RAM (latency in hundreds of microseconds vs. tens of nanoseconds). It serves as a buffer for sporadic spikes and to avoid OOM kill, not to run the normal workload. If the application is constantly swapping, RAM is insufficient — add physical memory.

What is the ideal swap size for a VPS?

Modern rule of thumb: 1 GB of swap for a VPS with 1-2 GB of RAM, 2 GB for a VPS with 2-4 GB, and 2-4 GB for any server with 4+ GB. The old '2x the RAM' rule came from the desktop hibernate era and makes no sense on a server. Do not exceed 4 GB of swap on a production VPS — if you are using that much, RAM is insufficient.

Should I use a swapfile or a swap partition?

Swapfile. On a VPS provisioned with a pre-built disk layout, creating a partition is complicated (involves repartitioning) and offers zero modern performance advantage. A swapfile is resizable, removable and works identically under real workload. Use a swap partition only on a physical server with a dedicated disk for swap.

What is swappiness and what value should I use on a server?

Swappiness (0-100) controls how aggressively the kernel moves inactive pages to swap. Ubuntu's default is 60, optimized for desktop. On a server, use 10 — only swap when memory pressure is real, keeping disk cache in RAM as much as possible. For databases (PostgreSQL, MySQL), use 1 or even 0 with cgroups configured.

How do I remove swap if I no longer need it?

Disable it with sudo swapoff /swapfile, remove the line from /etc/fstab so it does not mount on boot, and delete the file with sudo rm /swapfile. Confirm with swapon --show — it should return nothing. Do this before resizing (you cannot resize an active swapfile).

Why is my VPS using swap even with free RAM?

Normal behavior. The kernel proactively moves inactive pages to swap to free RAM for disk cache, even without immediate pressure. With swappiness=60 (default), this is fairly aggressive. Reduce it to 10 if it bothers you. Only treat it as an alert when swap is being actively read/written (vmstat showing si/so > 0 constantly) — that is when RAM is actually insufficient.

Topics:
Next steps Ryzen cloud with NVMe storage and always-on DDoS protection.Go live on a Hostini VPS →
Was this tutorial helpful?
Chat on WhatsApp