Linux Swap and Swapfile
Swap is a space on a disk that is used when the amount of physical RAM memory is full. When a Linux system runs out of RAM, inactive pages are moved from the RAM to the swap space.
Swap space can take the form of either a dedicated swap partition or a swap file. In most cases when running Linux on a virtual machine (VPS) a swap partition is not present so the only option is to create a swap file.
Add/Remove Swapfile Short Guide
Swap On
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
sudo nano /etc/fstab
/swapfile swap swap defaults 0 0
If fallocate
is not installed or you get an error message saying fallocate failed: Operation not supported
then use the following command to create the swap file:
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
Swap Off
sudo swapoff -a # sudo swapoff /swapfile
sudo rm -f /swapfile
sudo nano /etc/fstab
#/swapfile swap swap defaults 0 0
Check the swap and its usage
sudo swapon --show
sudo free -h
Swap On/Off Scripts
swap-on.sh
#!/bin/bash
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
sudo sed 's_^#/swapfile_/swapfile_' /etc/fstab -i
echo
sudo swapon --show
echo
sudo free -h
swap-off.sh
#!/bin/bash
sudo swapoff /swapfile
sudo rm -f /swapfile
sudo sed 's_^/swapfile_#/swapfile_' /etc/fstab -i
echo
sudo swapon --show
echo
sudo free -h
Adjusting the Swappiness Value
Swappiness is a Linux kernel property that defines how often the system will use the swap space. Swappiness can have a value between 0 and 100. A low value will make the kernel to try to avoid swapping whenever possible while a higher value will make the kernel to use the swap space more aggressively.
The default swappiness value is 60. You can check the current swappiness value by typing the following command:
cat /proc/sys/vm/swappiness
60
While the swappiness value of 60 is OK for Desktops, for production servers you may need to set a lower value. For example, to set the swappiness value to 10, type:
sudo sysctl vm.swappiness=10
To make this parameter persistent across reboots append the following line to the /etc/sysctl.conf
file:
sudo nano /etc/sysctl.conf
vm.swappiness=10
The optimal swappiness value depends on your system workload and how the memory is being used. You should adjust this parameter in small increments to find an optimal value.
References
- Linuxsize: How To Add Swap Space on Ubuntu 18.04
- Ask Ubuntu: How to delete a swap file in Ubuntu?
- itBeginner.net: How to tweak and optimize SSD for Ubuntu, Linux Mint