How to Add Swap Space on Ubuntu 18.04 and Above
Written by BiRU Thursday, 17 November 2022 06:42
Check Swap Information
Command to check swap size.
swapon --show
Output:
NAME TYPE SIZE USED PRIO
/dev/vda2 partition 512M 0B -2
Or you can check using free
command.
free -m
Output:
total used free shared buff/cache available
Mem: 981 130 326 0 524 707
Swap: 511 0 511
NOTE: If the output is empty, it means that swap space is not enabled yet on your system.
Add Swap to your VPS
Command to create a Swap file.
NOTE: We are adding 1GB if you want to add different size then you can replace it in place of 1G
fallocate -l 1G /swapfile
or
dd if=/dev/zero of=/swapfile bs=1024 count=1048576
Set write permission.[Default permissions only enable for root user]
chmod 600 /swapfile
Set up a swap area on the file.
mkswap /swapfile
Output:
Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=3f6fee94-ed65-4187-8c67-05afcd0c8ef1
Activate the swap file.
swapon /swapfile
Open the following file and add the given content to change it to permanent.
nano /etc/fstab
Add the following line.
/swapfile swap swap defaults 0 0
Now check the swap size.
swapon --show
or
free -m
Output:
root@vps:~# swapon --show
NAME TYPE SIZE USED PRIO
/dev/vda2 partition 512M 1M -2
/swapfile file 1024M 0B -3
root@vps:~# free -m
total used free shared buff/cache available
Mem: 981 126 65 0 789 706
Swap: 1535 1 1534
NOTE: Now the added swap space can be seen.
Remove Swap File
Deactivate the swap space.
swapoff -v /swapfile
Output:
root@vps:~# swapoff -v /swapfile
swapoff /swapfile
Next, remove the following line from the file /etc/fstab
/swapfile swap swap defaults 0 0
Command to remove the file.
rm /swapfile
This concludes our topic of configuring swap in ubuntu.