When physical RAM is already in use, VM instances use swap space as a short-term replacement for physical RAM.
Contents of RAM that aren’t in active use or that aren’t needed as urgently as other data or instructions can be temporarily paged to a swap file. This frees up RAM for more immediate use.
Calculate the swap space size
As a general rule, calculate swap space according to the following:
|Amount of physical RAM||Recommended swap space|
|2 GB of RAM or less||2x the amount of RAM but never less than 32 MB|
|More than 2 GB of RAM but less than 32 GB||4 GB + (RAM – 2 GB)|
|32 GB of RAM or more||1x the amount of RAM|
In this example dd command, the swap file is 4 GB (128 MB x 32):
$ sudo dd if=/dev/zero of=/swapfile bs=128M count=32
2. Update the read and write permissions for the swap file:
$ sudo chmod 600 /swapfile
3. Set up a Linux swap area:
$ sudo mkswap /swapfile
4. Make the swap file available for immediate use by adding the swap file to swap space:
$ sudo swapon /swapfile
5. Verify that the procedure was successful:
$ sudo swapon -s
6. Enable the swap file at boot time by editing the /etc/fstab file.
Open the file in the editor:
$ sudo nano /etc/fstab
Add the following new line at the end of the file, save the file, and then exit:
/swapfile swap swap defaults 0 0
$ htop and check
swp [ ] section.