Sometimes we need to add extra swap space in our Linux machine, so in this article, I’m going to show you how to add swap space to a Linux server.
We have two ways to adding swap space in Linux environment.
- Create swap space using the file.
- Use Hard disk to adding swap space.
Check existing swap details using free -m command.
Check swap partition details using 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 swap file so that only root user can access the swap file.
chmod 600 /swap_file
Enable swap area using mkswap command.
Add the below entry in the fstab file so that swap file become persistent across every reboot.
vi /etc/fstab /swap_file swap swap defaults 0 0
Finally enable the newly created swap file using swapon command.
# swapon /swap_file
Now check the swap details, swap increased from 4GB to 5GB.
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 partion using fdisk command and use this partition as swap space.
After adding 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.
How to use existing mount point as swap space
Using mkswap command we can convert existing disk partition in swap space.
Now enable swap space for newly created swap file just using swapon command.
Make sure the newly created swap file entry must be available in /etc/fstab so that the swap file is available automatically after reboot the system.
#vi /etc/fstab dev/sdb1 swap swap defaults 0 0
Check existing swap details
Using swapon -s command will help us to find the available swap space information.
Check existing memorty and swap details
The free -k command show the memory (RAM) and swap space information.