# Using SWAP in the Linux system
In limited memory environments, creating a swap file would make the system load more applications, but the performance may degrade due to the overhead of swapping between physical and virtual memory.
Check the swap stat
show swap list
swapon --show
Using Disk space
Create a swap and mount it
sudo fallocate -l 8G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon --priority 1 /swapfile
# persistent
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# 10 minimal, 60 default, 100 max
sudo sysctl -w vm.swappiness=60
Tip
Persistant the sysctl setting, can use drop-in configuration in /etc/sysctl.d/
Stop swap and delete it
sudo swapoff /swapfile
sudo rm /swapfile
# remove line from /etc/fstab
sudo vim /etc/fstab
Using ZRAM
Check kernel
lsmod | grep zram
# if not present, switch it on
sudo modprobe zram num_devices=1
Install (Debian)
sudo apt update
sudo apt install zram-config
Configuare
Setup zram size, half of mahcine ram in this case.
echo $(( $(grep MemTotal /proc/meminfo | awk '{print $2}') * 1024 / 2 )) | sudo tee /sys/block/zram0/disksize
Switch on
sudo mkswap /dev/zram0
# Manual start
sudo swapon /dev/zram0
# Auto start
sudo systemctl enable zram-config
sudo systemctl start zram-config
Switch off
sudo systemctl stop zram-config
Test the swap
install stress
sudo apt install stress
using stress to test the Swap usage.
# 4 process, 2GB each for 60 seconds
stress --vm 4 --vm-bytes 2G --timeout 60s