Virtual Memory(SWAP)

Virtual Memory(SWAP)

Check your current memory usage.

free -m
$ free -m
              total        used        free      shared  buff/cache   available
Mem:            990         164         197          38         628         584
Swap:             0           0           0

$ free -m
             total       used       free     shared    buffers     cached
Mem:           992        867        125         20         63        516
-/+ buffers/cache:        287        704
Swap:         1023          0       1023

Setting Swap File

Setting 4G size of the SWAP file.

sudo -s
cd /var
fallocate -l 4G swapfile.1
chmod 600 swapfile.1

Accroding to the security issue, please make sure this SWAP file can only read and write by root account

Enable SWAP

mkswap /var/swapfile.1
swapon /var/swapfile.1

Check current SWAP file path

$ swapon -s
$ swapon -s
Filename				Type		Size	Used	Priority
/var/swapfile.1                        	file    	4194300	0	-1

Auto enable your SWAP while you restart your ubuntu

Make sure your SWAP file path is /var/swapfile.1. If you have any custom SWAP file path, please change your SWAP file path to your custom path. If the SWAP file path not correct, your system might not able to boot correctly

echo "/var/swapfile.1    none    swap    sw    0    0" >> /etc/fstab

Using htop to monitor your memory usage

sudo apt-get install htop

Setting swappiness to adjust your SWAP priority

swappiness value is between 0~100. If the value is more close to 100, then the system will use SWAP more frequently. Vice versa, if the value is more close to 0, then the system will use the real RAM more frequently.

The default value is 60. If you want to improve your system’s performance. You can set this value more close to 0 to use more real RAM.

Check swappiness

cat /proc/sys/vm/swappiness

Setting swappiness

sysctl vm.swappiness=10

Setting swappiness after restart ubuntu

echo "vm.swappiness = 10" >> /etc/sysctl.conf

Change SWAP size

Close Swap

swapoff -a

Reset SWAP file size

Setting 8G size of the SWAP file.

sudo -s
cd /var
fallocate -l 8G swapfile.2
chmod 600 swapfile.2

Enable SWAP

mkswap /var/swapfile.2
swapon /var/swapfile.2

Reference