In this tutorial we will see how we can add SWAP space to our Linux box and also understand the use of SWAP space.
What is Swap ?
Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM.
Basically, this gives you the ability to increase the amount of information that your server can keep in its working "memory". The space on the hard drive will be used mainly when space in RAM is no longer sufficient for data.
Very important to understand is that the information written to disk will be slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a backup plan when your system's RAM is almost done and swap space will save your skin.
So now that we know what is SWAP and why we use it lets see how we can get information about our system SWAP, how we can add more SWAP or even remove SWAP space.
1.See if you have SWAP:
We can see if the system has any configured SWAP by typing:
no SWAP here !!!
Also free command with option -m can tell use about our SWAP
As you can see our total swap space in the system is 0.
2. Add SWAP
Before you add SWAP you need to make sure you have the disk space on your host, df command with option -h is a good candidate for this task.
ok we got some space left.
SWAP space can be added using the dd command or fallocate command.
dd - pre allocates a portion of the disk
you can use dd to write zeros to the file from a special device in Linux systems located at /dev/zero that just spits out as many zeros as requested.(pretty smart :) )
fallocate - creates a file of a pre allocated size instantly, without actually having to write dummy contents.
Create using dd:
the command will spit 1024 mb (zeross) into the file /SWAPfile
SWAP file create
Create using the fallocate:
this way is instant file allocation.
3.Enabling the Swap File
At this point we have the file created and we need to hand it to our operational system for use. Before we go ahead and do this we need to make sure this file can be read only by the root user.
Change file permissions:
Setup SWAP by using the mkswap command:
Make SWAP available now:
Verify that SWAP is there:
Great our system has SWAP space now but we need to make is permanent because at this point if we reboot the system the swap space will be lost.
What we need to do is add a new entry in out /etc/fstab file.
this will make sure that when reboot your system the swap file will be "mounted".
And we are done! There are more to add about Linux SWAP space but we will touch base about this on the next Tutorial - Manage SWAP space Settings in Linux