Adding a swap file to small Digital Ocean droplets on Ubuntu

If you have a smaller droplet on DigitalOcean, chances are you will need to create a swap file at some point. A good example of needing a swap file is if you get the following error in your daily cron:

FATAL -> Failed to fork.

The error above normally occurs when you run out of RAM needed to run the cron job. 

Just how much free RAM do you have? This is easy to check with 

# free -mh
             total       used       free     shared    buffers     cached
Mem:          490M       403M        86M       360K        17M       254M
-/+ buffers/cache:       131M       358M
Swap:           0B         0B         0B

A typical rule of thumb for creating a swap file is that you want a swapfile that is twice the amount of RAM you have. In our case, we are on a 500MB RAM droplet, so we will want to create a 1GB swap file. Before we create the file, let's ensure we have enough space on our drive:

# df -h
Filesystem                 Size  Used Avail Use% Mounted on
udev                       235M  4.0K  235M   1% /dev
tmpfs                       50M  404K   49M   1% /run
/dev/disk/by-label/DOROOT   20G  8.4G   11G  46% /
none                       4.0K     0  4.0K   0% /sys/fs/cgroup
none                       5.0M     0  5.0M   0% /run/lock
none                       246M     0  246M   0% /run/shm
none                       100M     0  100M   0% /run/user

In our case we have 8.4GB available, which is enough to create a 1GB swap file. So let's get started. For the purposes of this tutorial, we'll put the swap file in the root of the drive and call it 'swapfile'. We'll use fallocate which preallocates space to a file. The -l option specifies the length of the allocation (size of file) in bytes. You may us M or G to specify MB or GB:

# sudo fallocate -l 1G /swapfile
# sudo chmod 600 /swapfile
# ls -la /swapfile
-rw------- 1 root root 1048576000 May 30 09:17 /swapfile

Next, we will convert the regular file into a file that can be used as a swap file, and then enable the swap file:

# sudo mkswap /swapfile
# sudo swapon /swapfile
# sudo swapon -s
Filename Type Size Used Priority
/swapfile                               file 1023996 0 -1

If you run free -mh now you will see that the swapfile has been created and enable and is now ready for use:

# free -mh
             total       used       free     shared    buffers     cached
Mem:          490M       331M       158M       5.8M        21M       141M
-/+ buffers/cache:       169M       320M
Swap:         999M         0B       999M

The only thing left to do is add an entry to fstab to ensure the swap file persists between reboots:

echo "/swapfile   none    swap    sw    0   0" | sudo tee /etc/fstab -a

You should be set now!