Adding a swap file on Linux
A safe, repeatable way to add, tune, verify, and remove file-backed swap.
- Linux
- Operations
Loading post…
A safe, repeatable way to add, tune, verify, and remove file-backed swap.
Loading post…
A swap file can give a small Linux machine some breathing room when memory is tight. It is much slower than RAM, so it is a safety net rather than a performance upgrade.
These steps create a 4 GiB file. Check free disk space first with df -h /.
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Verify both memory totals and the active swap device:
free -h
swapon --show
dd is not the fastest way to allocate a file, but it is portable. Files created
with fallocate can be unsuitable on some filesystems, and Btrfs needs additional
copy-on-write handling.
Back up fstab, then add the entry only if it is not already present:
sudo cp /etc/fstab /etc/fstab.bak
grep -qF '/swapfile none swap defaults 0 0' /etc/fstab || \
echo '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstab
You can test the file before rebooting:
sudo swapoff /swapfile
sudo swapon -a
swapon --show
vm.swappiness influences how readily the kernel swaps anonymous memory. There is no
universally correct value; workload and memory pressure matter more than folklore.
To use a conservative value of 10 and make it persistent:
echo 'vm.swappiness = 10' | sudo tee /etc/sysctl.d/90-local-swap.conf
sudo sysctl --system
sysctl vm.swappiness
I would leave vm.vfs_cache_pressure at its default unless measurements show a
specific cache problem. Changing several memory knobs at once makes later diagnosis
harder.
Make sure the machine has enough available RAM before disabling active swap. Then:
sudo swapoff /swapfile
sudo sed -i.bak '\|^/swapfile[[:space:]]|d' /etc/fstab
sudo rm /swapfile
sudo rm -f /etc/sysctl.d/90-local-swap.conf
Run swapon --show once more; it should no longer list /swapfile.
The upstream swapon and
mkswap manual pages document
the filesystem restrictions and current options.
Comments
View on GitHub