Linux systems with low RAM are prone to have issues as available RAM is depleted.
This sequence creates a secure 1GB swap file, enables it, ensures it persists after reboot, and tunes how aggressively Linux uses swap. This is useful for systems with limited RAM.
sudo swapon --show
sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
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
sudo sysctl vm.swappiness=40
cat /proc/sys/vm/swappiness
A break down of what these series of steps are doing:
sudo swapon --show
Shows currently active swap areas. Useful for checking if swap is already enabled.
sudo fallocate -l 1G /swapfile
Allocates a 1GB file at /swapfile. This file will be used as swap space.
sudo chmod 600 /swapfile
Sets permissions so only root can read/write the swap file, which is important for security.
sudo mkswap /swapfile
Sets up the file as swap space by writing the swap area signature.
sudo swapon /swapfile
Activates the swap file, making it available for use immediately.
sudo cp /etc/fstab /etc/fstab.bak
Makes a backup of the /etc/fstab file, which lists filesystems and swap areas to mount at boot.
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Appends a line to /etc/fstab so the swap file is enabled automatically at boot.
sudo sysctl vm.swappiness=40
Sets the kernel’s swappiness parameter to 40 (on a scale of 0–100). Lower values mean the system will try to avoid swapping; higher values make it more likely to use swap.
cat /proc/sys/vm/swappiness
Displays the current swappiness value to confirm the change.