Creating swap file on your filesystem

Some times you just need more memory in your system that you physically have. You don't know what to do but you cannot add more memory for various reasons. Filesystem is always there is it has more space than you could need in memory so why not use it to create more memory space. Some people would say that it slows down the system or the application would run slower but it would give you an alternative for purchasing higher end VPS or bare metal systems with more memory which would cost alot of money.

So the first step is to identify if you have enough space on your system for the amount of swap you need to create. When you are ready do move forward you need to create an empty file of a certain size. In this example I will be using 2GB.

#dd if=/dev/zero of=/.swap bs=2M count=1024

dd is a tool with which you can create disk images of any type.
if = is the input file which is read instead of the stdin
of = is the output file where the data will be written instead of stdin
bs = read or write up the bytes configured
count = copy only count value input blocks

After the file was created we need to set it's proper mode to be only readable and writable by root.

#chmod 600 /.swap

Now it's time to create a filesystem on the 2GB file created

#mkswap /.swap

Once the file was created and it has a filesystem you can mount it using swapon command

#swapon /.swap

You can check the swap file by running free -h and you will see among other information the following:

#Swap:          2G         0B        2G

In case you want to load your swap file on boot time you need to add it into /etc/fstab by running the following command:

#echo "/.swap        swap    0   0" >> /etc/fstab

Note I used hidden file as a swap file because it would not show up on a simple file list without -a option.