Adding swap with a File in Your VPS

If you don’t have any additional disks, you can create a file somewhere on your filesystem, and use that file for swap space. Normally some vps providers don’t give swap. For those who has that type of vps will need this tutorial to get a swap to faster website or vps.

Linux divides its physical RAM (random access memory) into chucks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.


I will show you by adding 1024mb or 1gb swap space. Put below commands to your terminal and press enter.

dd if=/dev/zero of=/swap bs=1M count=1024

by above command you are creating 1024mb sized file naming swap which will be in / directory. If you change the 1024 number to whatever you want you will get that sized swap file. As 2048 for 2gb.

Now give permission to that file to accessed only by root.

chmod 600 /swap

Now let us make swap.

mkswap /swap

Now enable the swap.

swapon /swap

Now let us activate this swap as enable in every boot. Edit /etc/fstab file.

nano /etc/fstab

And put below line there (end). Do not paste , just write word by word , use TAB button to write word after word.

/swap               swap                    swap    defaults        0 0

And save. Now reboot. And check if it is working or not.

swapon -s

And also by :

free -m

Now if you want to turn off / turn on swap then use :

For Turning OFF:

swapoff -a


swapon -a


Thank You