Swap space is an area on disk that Linux uses when it runs out of physical RAM. When the system needs more memory than is available, it moves inactive pages from RAM to swap to free up space for active processes.
Swap can be a dedicated partition or a swap file. On virtual machines, a swap partition is usually not present, so a swap file is the go-to solution.
This guide shows you how to add swap space on Ubuntu 20.04, how to make it persist across reboots, and how to tune and remove it.
Swap is slower than RAM because it uses your hard drive. It helps prevent crashes when memory runs out, but it is not a replacement for more RAM. If your server constantly hits its memory limit, the real fix is to upgrade the RAM.
How much swap you need depends on how much RAM you have:
You need root or sudo access to create and activate a swap file.
This example creates a 2 GB swap file. Replace 2G with the size you need.
Create the swap file using fallocate:
bashsudo fallocate -l 2G /swapfile
If fallocate is not available or returns an error on your system, use this alternative:
bashsudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152
Set permissions to 600 so only root can read and write the file:
bashsudo chmod 600 /swapfile
Format the file as a Linux swap area:
bashsudo mkswap /swapfile
Activate the swap:
bashsudo swapon /swapfile
The swap is now active, but it will not survive a reboot yet. To make it permanent, open /etc/fstab:
bashsudo nano /etc/fstab
Add this line at the end of the file:
/swapfile swap swap defaults 0 0
Save and close the file. The swap file will now enable itself automatically on every boot.
Verify the swap is active:
bashsudo swapon --show
Or check with free:
bashsudo free -h
You should see swap listed in the output with its size and usage.
Swappiness controls how often Linux moves data from RAM to swap. It ranges from 0 to 100:
For most desktop systems, 60 is fine. For production servers, a lower value like 10 is often better because it keeps more working data in RAM and reduces disk activity.
Check the current swappiness value:
bashcat /proc/sys/vm/swappiness
Set a new value that takes effect right away but resets on reboot:
bashsudo sysctl vm.swappiness=10
To make the change permanent, open /etc/sysctl.conf and add:
vm.swappiness=10
The right swappiness value depends on your workload. Start at 10 for servers and adjust in small steps based on how your system behaves.
To fully remove the swap file, follow these steps in order.
Turn off the swap:
bashsudo swapoff -v /swapfile
Open /etc/fstab and delete the line:
/swapfile swap swap defaults 0 0
Then remove the swap file itself:
bashsudo rm /swapfile
Swap space is now set up and running on your Ubuntu server. It gives the system breathing room when RAM gets tight and helps prevent out-of-memory crashes. Keep the swappiness value tuned to match how your server actually uses memory. Got questions? Leave a comment below.