If we don’t have any additional disks, you can create a file somewhere on our filesystem, and use that file for swap space.
The following dd command example creates a swap file with the name “swapfile” under /root directory with a size of 2GB.
# dd if=/dev/zero of=/root/swapfile bs=1M count=2048
list the create file
# ls -l /root/swapfile
Change the permission of the created swap file so that only root can access it.
# chmod 600 /root/swapfile
Make this file as a swap file using mkswap command.
# mkswap /root/swapfile
Enable the newly created swapfile.
# swapon /root/swapfile
To make this swap file available as a swap area during reboot persistently, add the following line to the /etc/fstab entry.
# vim /etc/fstab
/root/swapfile swap swap defaults 0 0
Verify whether the newly created swap area is available for your use by running the status option.
# swapon -s
To see the Swap free size
# free -k
In the output of swapon -s command, the type column will say “file” if the swap space is created from a swap file.
To disable and enable all swap space use below commands.
# swapoff -a
# swapon -a
We have done with creating a swap space using the file.