SWAP is virtual memory outside of installed physical memory (RAM). Swap is useful when your server has limited RAM (under 2GB) or runs memory-hungry tasks. On servers with plenty of RAM and fast SSDs, swap can cause unnecessary disk writes — evaluate your workload before adding it.
Check the system to see if SWAP information already exists:
free -h
sudo swapon --show
The free -h output shows total, used, and available RAM plus swap usage in a human-readable format. If swapon --show returns nothing, no swap is configured.
Check free space on the partition:
df -h
Create a SWAP file. A 1G file is a good starting point; for servers with only 1-2GB of RAM, consider 2G:
sudo fallocate -l 1G /swapfile
Note: fallocate creates files quickly on ext4 but may fail on XFS, ZFS, or overlay filesystems. If you get an error, fall back to dd:
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
SWAP file permission check:
sudo chmod 600 /swapfile
ls -lh /swapfile
Enable SWAP space:
sudo mkswap /swapfile
sudo swapon /swapfile
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Optimizing SWAP settings:
sudo nano /etc/sysctl.conf
Add to the bottom of the file vm.swappiness=10 and vm.vfs_cache_pressure=50. A lower swappiness value tells the kernel to keep data in RAM longer, reducing swap usage on systems with enough memory.
Avoiding Swap
If your system has 16 GB or more RAM and uses SSDs, swap is rarely needed for daily workloads. Heavy swap writes shorten SSD lifespan. Reserve swap for servers with 1–4 GB RAM or workloads with unpredictable memory spikes.
For more on Linux memory management, see the kernel documentation on sysctl vm settings.
Related What I Do
Related What I Do
These What I Do pages are matched from the subject matter of this article, creating a cleaner path from educational content to implementation work.
Continue reading
Related articles
Based on shared categories first, then the strongest overlap in tags.