Tutorial

How to Add Swap Space on Ubuntu: Fix Out of Memory Crashes

April 24, 2026

Back to Blog

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.

The OOM killer does not care about your priorities. It uses a scoring algorithm that considers process size, age, and a few other factors. It might kill your database, your web server, or your application — whatever it calculates will free the most memory with the least impact. In practice, it often kills the most important process on the server because that is usually the one consuming the most RAM.

You can check if the OOM killer has been active on your server by searching the kernel logs:

$ dmesg | grep -i "out of memory" [ 432.891234] Out of memory: Killed process 2341 (mysqld) total-vm:2048576kB $ journalctl -k | grep -i "oom" Mar 15 03:42:11 server1 kernel: mysqld invoked oom-killer: gfp_mask=0x6200ca(GFP_HIGHUSER_MOVABLE)

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.

Application
requests memory
RAM full?
Move cold pages
to swap
Free RAM for
active process
Swap is not a RAM replacement. Disk I/O is orders of magnitude slower than RAM access. Swap prevents crashes, but if your server is heavily swapping, you will see severe performance degradation. Think of swap as a life jacket — it keeps you afloat in an emergency, but you should not be swimming in it all day.

Step 1: Check Existing Swap

Before creating swap space, verify what your server currently has.

$ free -h total used free shared buff/cache available Mem: 31Gi 4.9Gi 22Gi 256Mi 3.6Gi 25Gi Swap: 0B 0B 0B $ swapon --show (no output = no swap configured)

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.

1
Allocate the swap file. Use fallocate for instant allocation, or dd as a fallback for filesystems that do not support fallocate.
$ sudo fallocate -l 4G /swapfile # Or use dd as alternative for XFS/older ext4: $ sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress 4294967296 bytes (4.3 GB, 4.0 GiB) copied, 8.2 s, 524 MB/s
2
Set the correct permissions. Only root should be able to read and write the swap file. This is a security requirement — swap can contain sensitive data from process memory.
$ sudo chmod 600 /swapfile $ ls -lh /swapfile -rw------- 1 root root 4.0G Mar 17 12:00 /swapfile
3
Format the file as swap. The mkswap command writes the swap signature header.
$ sudo mkswap /swapfile Setting up swapspace version 1, size = 4 GiB (4294963200 bytes) no label, UUID=a1b2c3d4-e5f6-7890-abcd-ef1234567890
4
Activate the swap file. This makes it available immediately, but it will not survive a reboot yet.
$ sudo swapon /swapfile $ swapon --show NAME TYPE SIZE USED PRIO /swapfile file 4G 0B -2 $ free -h total used free shared buff/cache available Mem: 31Gi 4.9Gi 22Gi 256Mi 3.6Gi 25Gi Swap: 4.0Gi 0B 4.0Gi
Swap is active! Your server now has 4 GB of swap space. But this is temporary — it will disappear on reboot unless we make it permanent.

Step 3: Make Swap Permanent

To persist swap across reboots, add an entry to /etc/fstab.

$ echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab $ cat /etc/fstab | grep swap /swapfile none swap sw 0 0
Always verify /etc/fstab after editing! A syntax error in fstab can prevent your server from booting. Run 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 RAMRecommended SwapReasoning
1 GB2 GBSmall VPS needs generous swap as a safety buffer
2 GB2-4 GBCommon for web servers; equal to or double RAM
4 GB2-4 GBEqual to RAM is sufficient
8 GB4 GBHalf of RAM provides adequate buffer
16 GB4-8 GBLarge buffer against memory spikes
32 GB+4-8 GBDiminishing returns; swap is for emergencies, not regular use
64 GB+4 GBMinimal swap just to prevent OOM; at this scale, add RAM instead
Database servers: If you run MySQL or PostgreSQL with large buffer pools, keep swap modest (4 GB max) and focus on having enough RAM. Swapping database buffer pages to disk defeats the purpose of the buffer pool and causes extreme I/O latency.

Tuning Swappiness

The swappiness parameter controls how aggressively the kernel swaps memory pages to disk. It is a value between 0 and 100.

0
Minimum Swappiness

The kernel avoids swapping unless absolutely necessary (RAM is completely exhausted). Good for database servers where RAM access speed is critical.

60
Default Swappiness

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

$ cat /proc/sys/vm/swappiness 60 $ sudo sysctl vm.swappiness=10 # Temporary (until reboot) vm.swappiness = 10 $ echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf # Permanent $ sudo sysctl -p # Apply sysctl.conf now

Recommended Swappiness by Workload

WorkloadSwappinessWhy
Database server (MySQL, PostgreSQL)1-10Prevent buffer pool pages from being swapped
Web server (nginx + PHP-FPM)10-20Keep worker processes in RAM
Application server (Go, Node.js)10-20Application code should stay in RAM
Shared hosting (many users)20-30Some swapping is acceptable to serve more users
Desktop / Development60Default 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.

$ cat /proc/sys/vm/vfs_cache_pressure 100 $ sudo sysctl vm.vfs_cache_pressure=50 $ echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf

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
In practice: On modern enterprise SSDs, swap wear is negligible unless your server is constantly thrashing swap. If your server regularly uses more than 10-20% of its swap, you have a RAM problem, not a swap problem. Add more RAM rather than worrying about SSD wear.

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)

$ free -h total used free shared buff/cache available Mem: 31Gi 4.9Gi 22Gi 256Mi 3.6Gi 25Gi Swap: 4.0Gi 128Mi 3.9Gi

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)

$ vmstat 5 10 # Print stats every 5 seconds, 10 times procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu----- r b swpd free buff cache si so bi bo in cs us sy id wa st 1 0 131072 23240 4096 3768832 0 0 4 12 234 456 3 1 96 0 0 2 0 131072 23128 4096 3768844 0 0 0 28 312 523 5 2 93 0 0

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

$ for pid in /proc/[0-9]*; do name=$(cat $pid/comm 2>/dev/null) swap=$(awk '/VmSwap/{print $2}' $pid/status 2>/dev/null) [ -n "$swap" ] && [ "$swap" -gt 0 ] && echo "$swap kB $name" done | sort -rn | head -10 52428 kB mysqld 12288 kB php-fpm 8192 kB postfix 4096 kB dovecot

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

$ sudo swapoff /swapfile # Deactivate (moves data back to RAM) $ sudo rm /swapfile # Delete the file # Remove the /swapfile line from /etc/fstab
Warning: 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.

$ sudo swapoff /swapfile $ sudo fallocate -l 8G /swapfile # New size: 8 GB $ sudo chmod 600 /swapfile $ sudo mkswap /swapfile $ sudo swapon /swapfile $ free -h | grep Swap Swap: 8.0Gi 0B 8.0Gi

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.

$ sudo swapon /swapfile-ssd --priority 100 # Fast SSD swap, used first $ sudo swapon /swapfile-hdd --priority 10 # Slow HDD swap, overflow only $ swapon --show NAME TYPE SIZE USED PRIO /swapfile-ssd file 4G 0B 100 /swapfile-hdd file 8G 0B 10

In /etc/fstab, use pri=100 and pri=10 to set priorities:

/swapfile-ssd none swap sw,pri=100 0 0 /swapfile-hdd none swap sw,pri=10 0 0

Complete Setup Script

Here is a complete script that creates swap, sets swappiness, and makes everything permanent:

#!/bin/bash SWAP_SIZE="4G" SWAPPINESS=10 CACHE_PRESSURE=50 # Check if swap already exists if swapon --show | grep -q '/swapfile'; then echo "Swap already exists. Exiting." exit 0 fi # Create and activate swap fallocate -l $SWAP_SIZE /swapfile chmod 600 /swapfile mkswap /swapfile swapon /swapfile # Make permanent echo '/swapfile none swap sw 0 0' >> /etc/fstab # Tune swappiness and cache pressure sysctl vm.swappiness=$SWAPPINESS sysctl vm.vfs_cache_pressure=$CACHE_PRESSURE echo "vm.swappiness=$SWAPPINESS" >> /etc/sysctl.conf echo "vm.vfs_cache_pressure=$CACHE_PRESSURE" >> /etc/sysctl.conf echo "Swap setup complete:" free -h | grep Swap

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 + swapon to create swap in seconds
  • Add to /etc/fstab to 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
Monitoring made easy: Panelica's dashboard displays real-time memory and swap usage per user, making it easy to identify which accounts are consuming the most resources and whether your server needs a RAM upgrade. Combine this visibility with the swap configuration from this guide for a well-tuned server.
Share:
See the Demo