Swap space on Linux
Swap is disk space that the Linux kernel uses as an overflow for memory: rarely used memory pages are moved there so RAM stays free for active work. It can be a dedicated partition or a swap file, and it is shown by the commands free -h and swapon --show.
1Why swap is still useful
Even with plenty of RAM, swap lets the kernel move idle pages out of memory and gives a buffer before the out-of-memory killer stops processes. Heavy, constant swapping, however, means the machine needs more RAM or fewer workloads.
2Swappiness
The kernel setting vm.swappiness (0-200, default 60) influences how readily the kernel swaps compared with dropping file cache. Lower values keep application memory in RAM longer. It is read with sysctl vm.swappiness and set permanently in a file under /etc/sysctl.d/.
3Swap files
A swap file is created, formatted with mkswap, enabled with swapon and added to /etc/fstab to survive reboots. Its permissions must be 600.
How to add a 2 GB swap file
- Create the file:
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 - Restrict access:
sudo chmod 600 /swapfile - Format it:
sudo mkswap /swapfile - Enable it:
sudo swapon /swapfile - Make it permanent: add the line '/swapfile none swap sw 0 0' to
/etc/fstab - Check:
swapon --showandfree -h
Cautions
- On Btrfs a swap file needs special preparation (no copy-on-write); follow your distribution's guide.
- A mistake in
/etc/fstabcan stop the system from booting: check the line before rebooting.
Related articles
- df (disk free)How to read df output, why Use% can reach 100% before Avail is zero for normal users, and how to check inodes with df -i.
- systemd units and systemctlWhat a systemd unit is, the common unit types, and how to start, stop, enable and inspect services with systemctl.
- Disk usage with du and ncduHow to find what fills a Linux disk with du and the interactive ncdu, with options that stay on one file system.
Sources
- swapon(8) man7.org
- mkswap(8) man7.org
- free(1) man7.org
- Documentation for /proc/sys/vm (kernel.org) kernel.org
Last reviewed: