Sometimes we need to add extra swaps to our Linux machine, so in this article, I'm going to show you how to add swap space.
We have two ways to add swap in the Linux environment.
- Create swap space using the file.
- Use Hard disk to adding swap space.
Check existing swap details using the free -m command.
free -m
Check swap partition details using swapon -s.
swapon -s
1. Create swap space using file
Creating swap space using the dd command, here we are going to create a swap file named swap_pfile as ROOT user.
dd if=/dev/zero of=/swap_file bs=1G count=1
The above command will create a swap file with the name swap_file inside the root directory with the size of 1024MB (1GB).
Now we need to change the permission of the swap file so that only the root user can access the swap file.
chmod 600 /swap_file
Enable swap area using the mkswap command.
mkswap /swap_file
Add the below entry in the fstab file so that the swap file becomes persistent across every reboot.
vi /etc/fstab
/swap_file swap swap defaults 0 0
Finally, enable the newly created swap file using the swapon command.
# swapon /swap_file
Now check the swap details, swap increased from 4GB to 5GB.
free -m
swapon -s
2. Use Hard disk to adding swap space
If you have free space in your existing hard drive or you have any extra hard disk then create a partition using the fdisk command and use this partition as swap space.
Read - how to add new hard disk in Linux
After adding a new hard disk in Linux, just follow the below steps.
Check existing disk partition using fdisk -l command, in my case the /dev/sdb1 is free which is 10GB size.
#fdisk -l
How to use existing mount point as swap space
Using the mkswap command we can convert the existing disk partition in swap space.
#mkswap /dev/sdb1
Enable swap
Now enable swap space for newly created swap file just using swapon command.
#swapon /dev/sdb1
Make sure the newly created swap file entry must be available in /etc/fstab so that the swap file is available automatically after rebooting the system. This is the way to add SWAP Space in Linux.
#vi /etc/fstab
dev/sdb1 swap swap defaults 0 0
Check existing swap details
Using the swapon -s command will help us to find the available swap space information.
Check existing memorty and swap details
The free -k command shows the memory (RAM) and swap space information.
One thought on “How to add SWAP Space in Linux”