Use the "SWAP" (on your VPS)

SWAP space can be a life saver.

If your are like me, you may often find yourself messing with VPSes and other servers. All too often these are provisioned with very little RAM, 512MB or less.
When your applications/processes run out of RAM, most of them become relatively unhappy and begin to behave erradically and finally crash.
In many cases you only need more RAM temporarily while you run some memory intensive command or perhaps you just want a safty net. SWAP space offers you this flexibillity by tapping into your hard drive's space. Imagine it as emergency RAM which lives on your hard drive in the form of a file or partition. In the event that more RAM is need than available, the OS will automatically tap that file instead of crashing your programs. The only down side is that SWAP is many times slower than your physical RAM and will therefore affect your overall performance.

Creating a SWAP file

Log into your machine over ssh or locally, then we will create a 512mb file full of zeros using dd and finally we will make it only read-writable by root.

sudo dd if=/dev/zero of=/swapfile bs=1024 count=524288
sudo chown root:root /swapfile
sudo chmod 600 /swapfile

now we will turn this file into a swapfile format using mkswap:

sudo mkswap /swapfile

Swapping the swapfile on:

 sudo swapon /swapfile

To check whether it worked or not check the output of free -m for the line specifying swap:

derp@box:~$ free -m
         total       used       free     shared    buffers     cached
Mem:           491        484          6          0         21        169
-/+ buffers/cache:        293        198
Swap:          511          0        511

In the above example it looks like everything went well. Now we have to make it permanent, otherwise at every reboot you would need to run the swapon command again. This is where our friend fstab comes in.

sudo nano /etc/fstab

Add the following line at the bottom:

/swapfile       swap    swap    defaults        0       0

This will mount the swap file at boot with default options.

Cheers and enjoy your swapping.

Also sidenote: VPSes and other servers with fast disks will do much better when swapping. I can recommend Digital Ocean, all their VPSes are backed by SSD, which makes running in swap very quick.