How to add Swap partition in Debian/Ubuntu

RAM is composed of chunks of memory called Pages.  When programs execute, it takes fills up pages. Due to this sooner or later memory will run out. In order to free up the RAM, Pages can be swapped into hard drive and the freed up RAM can be used by the other program which needs CPU’s attention.
Swap space is not a must in Linux. So if you happen to have a system that does not have Swap space, then follow the below guide to create a swap file and use it.
Check whether a SWAP space is enabled
sudo swapon -s
if you do not have swap enabled in the system you should see the output as below
Filename                                Type            Size    Used    Priority
Check the system for available space.
The recommended swap file size is twice the size of the RAM size. If your RAM
size is 512 MB, then the SWAP file size should be 1GB.
df
Filesystem           1K-blocks      Used        Available Use% Mounted on
/dev/vda              20642428   2367536    17226316  13% /
tmpfs                   254432         0                  254432   0% /lib/init/rw
udev                    249612        60                   249552   1% /dev
tmpfs                   254432         4                    254428   1% /dev/shm
Allocate space for swapfile
sudo fallocate -l 1GB  /swapfile
Create Swap file 
sudo mkswap /swapfile
the output will look like below
Setting up swapspace version 1, size = 8388608 KiB
no label, UUID=103c4545-5fc5-47f3-a8b3-dfbdb64fd7eb
Turn on the SWAP file
sudo swapon  /swapfile
You will then be able to see the new swap file when you view the swap summary.
swapon -s
Filename    Type  Size Used Priority
/swapfile                               file  8388608 0 -1
TO add this partition permanently, add it into /etc/fstab
sudo nano /etc/fstab
/swapfile  none  swap  sw  0  0
save and close the fstab file.
Share: