Add File for Additional Swap Space

If you don’t have any additional disks, you can create a file somewhere on your 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 1024MB (1GB).


# dd if=/dev/zero of=/root/swapfile bs=1M count=1024
1024+0 records in
1024+0 records out

Change the permission of the swap file, only allow root access.


# chmod 600 /root/swapfile

Using mkswap command make this file as a swap file.


# mkswap /root/swapfile
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=########-####-####-####-############

Enable the newly created swapfile.


# swapon /root/swapfile

Using your favourite text editor, append the following line to the /etc/fstab file, to make this swap file available as a swap area even after a reboot.


# nano /etc/fstab
/root/swapfile swap swap defaults 0 0

Verify the newly created swap area.


# swapon -s
Filename                                Type            Size    Used    Priority
/dev/xvdb                               partition       524284  0       -1
/root/swapfile                          file            1048572 0       -2

To verify whether the system takes all the swap space mentioned in the /etc/fstab without rebooting, you can do the following, which will disable and enable all the swap partition mentioned in the /etc/fstab

#swapoff -a

#swapon -a

#swapon -s
Filename                                Type            Size    Used    Priority
/dev/xvdb                               partition       524284  0       -1
/root/swapfile                          file            1048572 0       -2