How to add a 2G swap file to a server

Some cloud servers do not come with swap. There are many arguments about why this is a good thing, and other arguments as to why it is bad. However sometimes you just want that extra buffer for one reason or another. So here is a quick way to add a 2G swap file to an existing cloud server:

Create the initial 2G file

mkdir /opt/swapfiles
touch /opt/swapfiles/2G-swap
dd if=/dev/zero of=/opt/swapfiles/2G-swap bs=1024 count=2097152

Now set it up to be swap, and enable it:

mkswap /opt/swapfiles/2G-swap
chmod 600 /opt/swapfiles/2G-swap
swapon /opt/swapfiles/2G-swap

Set it in /etc/fstab so it will persist across reboots

vi /etc/fstab
# Add
/opt/swapfiles/2G-swap none swap sw 0 0

Confirm your vm.swappiness is not set to 0:

vi /etc/sysctl.conf
# Change
vm.swappiness = 0
# To
vm.swappiness = 10

Finally, update the sysctl without having to reboot:

sysctl vm.swappiness=10

You can confirm the swap space is now active by:

free -h
             total       used       free     shared    buffers     cached
Mem:          990M       905M        85M        43M       124M       527M
-/+ buffers/cache:       253M       736M 
Swap:         2.0G         0B       2.0G