It happens without warning. One moment your server is humming along, serving requests and processing data. The next moment, your application crashes, your database stops responding, and you find cryptic "Killed" messages in your logs. The culprit? The OOM (Out of Memory) killer, Linux's last resort for dealing with memory exhaustion. The fix? Adding swap space. In this comprehensive guide, we will walk through everything you need to know about swap on Ubuntu servers — from understanding why you need it to creating swap files, tuning performance, and monitoring memory usage.
Understanding the OOM Killer
When your server runs out of physical RAM and has no swap space, the Linux kernel activates the OOM killer. This is a survival mechanism: rather than allowing the entire system to freeze, the kernel selects a process to terminate and free memory.
You can check if the OOM killer has been active on your server by searching the kernel logs:
If you see messages like these, your server has been killing processes to survive. Swap space is your safety net against this scenario.
What Is Swap Space?
Swap is a designated area on your disk that the kernel uses as an extension of RAM. When physical memory gets tight, the kernel moves less-frequently-used memory pages to swap, freeing up RAM for active processes. This is called swapping out. When a process needs those pages again, they are swapped in from disk back to RAM.
requests memory
to swap
active process
Step 1: Check Existing Swap
Before creating swap space, verify what your server currently has.
If the Swap line shows 0B across the board and swapon --show produces no output, your server has no swap space at all. This is common on VPS providers like Hetzner, DigitalOcean, and Linode — they ship servers with zero swap by default.
Step 2: Create a Swap File
Modern Linux systems use swap files instead of swap partitions. Swap files are easier to create, resize, and remove. Here is the complete process.
fallocate for instant allocation, or dd as a fallback for filesystems that do not support fallocate.
mkswap command writes the swap signature header.
Step 3: Make Swap Permanent
To persist swap across reboots, add an entry to /etc/fstab.
sudo findmnt --verify after any change to check for errors before rebooting.
Choosing the Right Swap Size
The "right" swap size depends on your server's RAM, workload, and whether you need hibernation (rare for servers). Here are practical recommendations for server workloads:
| Server RAM | Recommended Swap | Reasoning |
|---|---|---|
| 1 GB | 2 GB | Small VPS needs generous swap as a safety buffer |
| 2 GB | 2-4 GB | Common for web servers; equal to or double RAM |
| 4 GB | 2-4 GB | Equal to RAM is sufficient |
| 8 GB | 4 GB | Half of RAM provides adequate buffer |
| 16 GB | 4-8 GB | Large buffer against memory spikes |
| 32 GB+ | 4-8 GB | Diminishing returns; swap is for emergencies, not regular use |
| 64 GB+ | 4 GB | Minimal swap just to prevent OOM; at this scale, add RAM instead |
Tuning Swappiness
The swappiness parameter controls how aggressively the kernel swaps memory pages to disk. It is a value between 0 and 100.
The kernel avoids swapping unless absolutely necessary (RAM is completely exhausted). Good for database servers where RAM access speed is critical.
Ubuntu's default. The kernel actively swaps to keep free RAM available. Too aggressive for most servers — wastes disk I/O on unnecessary swapping.
Check and Change Swappiness
Recommended Swappiness by Workload
| Workload | Swappiness | Why |
|---|---|---|
| Database server (MySQL, PostgreSQL) | 1-10 | Prevent buffer pool pages from being swapped |
| Web server (nginx + PHP-FPM) | 10-20 | Keep worker processes in RAM |
| Application server (Go, Node.js) | 10-20 | Application code should stay in RAM |
| Shared hosting (many users) | 20-30 | Some swapping is acceptable to serve more users |
| Desktop / Development | 60 | Default is fine for interactive use |
VFS Cache Pressure
Related to swappiness is vfs_cache_pressure, which controls how aggressively the kernel reclaims memory used for directory and inode caches.
A value of 50 tells the kernel to prefer keeping directory/inode information in cache (which speeds up file operations) rather than reclaiming it aggressively. This is a solid setting for web servers that serve many files.
Swap on SSD Considerations
Most modern servers use SSDs, which have different characteristics than spinning disks when used for swap.
SSD Advantages for Swap
- Random read/write latency is orders of magnitude better than HDD
- Swap-in operations are much faster, reducing latency spikes
- No seek time penalty for random access patterns
SSD Considerations
- Write amplification: frequent swap writes increase SSD wear
- Enterprise SSDs have high endurance (TBW), less of a concern
- Consumer SSDs: keep swap small, swappiness low
- NVMe SSDs: swap latency is minimal, but still slower than RAM
Monitoring Memory and Swap Usage
Setting up swap is not a "set and forget" task. Regular monitoring helps you catch memory issues before they become crises.
free -h (Quick Overview)
Key columns to watch: available (not free) tells you how much memory is truly available for new processes. Linux uses free memory for caching, so free is often misleadingly low.
vmstat (Continuous Monitoring)
Watch the si (swap in) and so (swap out) columns. If so is consistently above zero, your server is actively pushing data to swap. Occasional spikes are normal; sustained values mean you are running low on RAM.
Per-Process Swap Usage
This one-liner shows which processes have been partially swapped out. If your database tops the list, that is a strong signal you need more RAM.
Removing or Resizing Swap
Removing a Swap File
swapoff can take a long time if a lot of data is in swap, because it must move everything back to RAM. If RAM is insufficient to hold all the swapped data, swapoff will fail or trigger OOM. Always check free -h first to ensure enough RAM is available.
Resizing Swap
You cannot resize a swap file in place. The process is: deactivate the old one, create a new one at the desired size, and activate it.
Multiple Swap Files with Priority
If you have multiple disks, you can create swap files on each with different priorities. Higher priority swap is used first.
In /etc/fstab, use pri=100 and pri=10 to set priorities:
Complete Setup Script
Here is a complete script that creates swap, sets swappiness, and makes everything permanent:
Troubleshooting Common Issues
"swapon: /swapfile: read swap header failed"
You forgot to run mkswap /swapfile before swapon. The file exists but has no swap header.
"swapon: /swapfile: insecure permissions 0644"
Run chmod 600 /swapfile. The kernel refuses to activate swap files that are world-readable for security reasons.
"fallocate: fallocate failed: Operation not supported"
Your filesystem (likely XFS or an older ext4) does not support fallocate. Use the dd command with /dev/zero as a source instead.
"swapoff: /swapfile: swapoff failed: Cannot allocate memory"
Not enough free RAM to absorb swap contents. Free up memory first (stop non-essential services), then try again.
Summary
- Swap space prevents OOM killer from terminating critical processes
- Use
fallocate+mkswap+swaponto create swap in seconds - Add to
/etc/fstabto persist across reboots - Set swappiness to 10-20 for server workloads (default 60 is too aggressive)
- Monitor with
free -h,vmstat, and per-process swap checks - Swap is a safety net, not a RAM substitute — sustained swapping means you need more RAM