SWAP memory is obviously very important in most Linux distributions, especially in a web hosting server environment. SWAP memory relies on disk (storage) and is very useful when virtual machines run out of memory.
On this tutorial, we will use a 1GB droplet from Digital Ocean which running on Ubuntu 20.04 LTS (Focal Fossa). So we can set 1GB SWAP memory for this virtual machine.
The following guide can be applied on all Linux distributions like CentOS/Fedora, Debian/Ubuntu, and the guys.
1.) Create SWAP File and Enable it
$ sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k 1048576+0 records in 1048576+0 records out 1073741824 bytes (1.1 GB, 1.0 GiB) copied, 2.95939 s, 363 MB/s
$ sudo mkswap /swapfilemkswap: /swapfile: insecure permissions 0644, 0600 suggested. Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
$ sudo swapon /swapfile swapon: /swapfile: insecure permissions 0644, 0600 suggested.
$ swapon -s Filename Type Size Used Priority /swapfile file 1048572 0 -2
2.) Open fstab file and add the following snippet code at the end of the file
$ nano /etc/fstab
/swapfile swap swap defaults 0 0
3.) Set Correct Permission for SWAP File
$ chown root:root /swapfile $ chmod 0600 /swapfile
4.) Make SWAP Memory to Run Automatically from Boot
Insert this snippet code at the end of the file
$ nano /etc/sysctl.conf
# Do less swapping vm.swappiness = 75 vm.dirty_ratio = 30 vm.dirty_background_ratio = 5
$ sysctl -p vm.swappiness = 75 vm.dirty_ratio = 30 vm.dirty_background_ratio = 5
To verify that the SWAP memory is set correctly, just run the following command:
$ free -m total used free shared buff/cache available Mem: 981 202 67 5 711 625 Swap: 1023 0 1023
Well, you now have 1GB SWAP Memory on your virtual machine. However, if you want to set SWAP memory for more than 1GB, for example if you currently use a dedicated server and want to set SWAP files up to 2GB/3GB/4GB/8GB and so on, you can change the value of 1024K to 2048K, 3072K, 4096K, 8192K, and so on.