Ubuntu Swap

Written by Rich Banks on 8th Mar, 2016


I recently had a problem where my Laravel Simple Backup task was being killed by Ubuntu due to a "Cannot Allocate Memory" issue. Composer was also running extremely slowly and sometimes showing a 'proc_open(): fork failed - Cannot allocate memory' error.

After a little Googling, I found that a simple fix would be to enable swap space on the server. I am running an Amazon t2.micro EC2 instance which only has 1GB of RAM so for me 1GB swap space should be sufficient. You may find you would like to have a larger swap file.

Firstly you should check if your system already has any configured swap.

free -m

The output shoule be similar to below. If you do not have swap configured 'Sawp:' should show 0 0 0 like below.

total       used       free     shared    buffers     cached
Mem:           992        921         71         44          3        130
-/+ buffers/cache:        787        205
Swap:            0          0          0

It is now a good idea to check that you have enough hard disk space for you swap file.

df -h

Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1      7.8G  2.0G  5.5G  27% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
udev            492M  8.0K  492M   1% /dev
tmpfs           100M  344K   99M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            497M     0  497M   0% /run/shm
none            100M     0  100M   0% /run/user

If you are happy you have enough space for your swap file you can create the file and enable it.

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

If you encounter any errors when running the above commands, try running them as sudo. You can change the size of the swap file by editing 'bs=' and 'count='

Swap should now be enabled. You can check by running.

free -m

total       used       free     shared    buffers     cached
Mem:           992        905         86         44          3        114
-/+ buffers/cache:        787        205
Swap:         1023          0       1023

This has worked well for me on Ubuntu 14.04.2.