We will create a file at the root of the system using the commands below.
dd if=/dev/zero of=/PATH/FILENAME bs=1024 count=SIZE
chmod 600 /PATH/FILENAME
mkswap /PATH/FILENAME
swapon /PATH/FILENAME
The “SIZE” must be in kilobytes (for example, 1048576 is 1 gigabyte).
In our case, we want to have 2G of swap (RAM).
If the swap (the /swapfile file) already exists, it must be disabled:
sudo swapoff -a
creation of the 2GB file.
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152
Next, we protect and activate our swap:
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
sudo swapon -a
View status:
swapon -s
#or
sudo cat /proc/swaps
Change priority:
sudo swapoff /swapfile
sudo swapon -p 50 /swapfile
sudo swapon -a
Install zram:
apt install zram-tools
Edit config zram:
sudo nano /etc/default/zramswap
Reload service :
sudo service zramswap reload
Save permanently:
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
sudo mount -a
The swappiness parameter configures the frequency at which your system swaps data from RAM to swap space. It is a value between 0 and 100 that represents a percentage.
With values close to zero, the kernel will not swap data to disk unless absolutely necessary. Keep in mind that interactions with the swap file are “expensive” in the sense that they take much longer than interactions with RAM and can result in a significant reduction in performance. Telling the system not to rely too much on swap will generally make your system faster.
Values closer to 100 will attempt to put more data into swap in order to keep more RAM free. Depending on the memory profile of your applications or the reason you are using your server, this may be preferable in some cases.
See the current value:
cat /proc/sys/vm/swappiness
Set a value :
sudo sysctl vm.swappiness=10
Set a permanent value :
Edit the /etc/sysctl.conf file and add :
vm.swappiness=10