1. Create a swap file of the desired size
We use the dd command to create and copy the file we will be using as the swap file.
As an example, lets create a swap file of 1 GB size -
# dd if=/dev/zero of=/my-swap-file bs=1024 count=1024000
The options passed to the dd command are as follows -
if=/dev/zero - Says to read from /dev/zero instead of stdin.
of=/my-swap-file - Asks the command to write the output to the file /my-swap-file.
bs=1024 - Block size, read and write up to 1024 bytes at a time. The optimum block size is hardware dependent but 512 to 1024 is a fair value to use.
count=1024000 - Copy only 1024000 input blocks; [1024 * 1000 MB]
2. Set the correct permission for the swap file
# chown 600 /my-swap-file
Make the permissions read and write for owner and no permissions for group and others. For security reasons, it is prudent to restrict access to the swap file to people with adminstrative powers - usually root.
3. Prepare the swap file
For this you use the mkswap command.
# mkswap /my-swap-file
4. Activate the swap file
Use the swapon command to activate the swap file so the system can start using it.
# swapon /my-swap-file
Finally, if you want the swap file to be available across reboots, you need to append the following line to the /etc/fstab file.
/my-swap-file swap swap defaults 0 0
The above line tells Linux to mount the swap file during boot time.
Save and close the /etc/fstab file.