Tuesday, May 13, 2014

How to setup file-based swap space on CentOS

In the name of Allah, Most Gracious, Most Merciful

In this article i will be configuring file-based swap space on CentOS. We often need to have swap space for larger programs to run properly. You can have swap partition for this purpose and also file-based swap space. File-based swap space is a quick way to setup swap file system. This method is tested on CentOS 6.5 but will work on Redhat 6. 5 as well. Lets do it.

First we need to check current swap space configured on system. Use following command to check it. You should be logged in as root user or use sudo with these commands.

swapon -s

It will print all swap file system, either file-based or partitioned-based. If nothing comes out then it means no swap space is configured. Lets add a 2GB file-based swap space.

dd if=/dev/zero of=/swapfile bs=1024 count=2048K

2097152+0 records in
2097152+0 records out
2147483648 bytes (2.1 GB) copied, 7.90701 s, 272 MB/s


if=/dev/zero means read from /dev/zero file which will provide null characters
of=/swapfile means write /dev/zero characters to this file.
bs=1024 means read and write 1024 bytes at a time
count=2048K means copy this many input blocks.

Lets make /swapfile a swap file system.

mkswap -f /swapfile

Setting up swapspace version 1, size = 2097148 KiB
no label, UUID=5c109315-3512-45db-8771-a0ecd7ac11e1


Lets change ownership of this file to root and grant read and write permission to everyone.

chown root:root /swapfile
chmod 666 /swapfile

Lets activate this swap space and verify it.

swapon -a /swapfile
swapon -s

Filename                Type            Size    Used    Priority
/swapfile               file            2097144 0       -1


This swap space will only available as long as system is up and running, and is cleared on system reboot.

Lets make is permanent, we need to add it to /etc/fstab. add following line to end of /etc/fstab

/swapfile swap swap defaults 0 0



I hope it will serve the purpose.