Add Swap Space to Amazon EBS on Linux EC2 Web Servers

Posted on November 16, 2012

This guide will walk you through setting up Swap space in an Amazon EC2 virtual Linux environment. For this example, I am running Centos 6, but the commands are more or less the same across the various Linux OS'. Swap space should not be seen as a replacement for memory, but rather an extension – a way to get a bit more out of the available memory.

Ideally, swap space would be allocated to an ephemeral volume, since the data does not need to persist, and there is no charge for I/O operations. However, since the t1.micro instance does not support ephemeral disks (and is, arguably, the instance most in need of swap space) we will look at setting up swap space on an EBS volume, below.

We start by creating an EBS volume – the smallest size is 1GB, which should be more than enough.

Attach the EBS volume to the instance – note the device you set it to (in my case, /dev/xvdg). To see which devices are active on your instance:

Setup the swap area (the -f option is to force the command to proceed – omit it if you are unsure about the target):

In order to have the swap space available after a boot, we edit /etc/fstab, adding the line below:

Finally, we can turn on swap (without a reboot), but issuing the command below.

You can verify that the swap space is active with the ‘free’ command. As an example, the output below is from one of my t1.micro instances that has been running for 15 days. The last line shows swap (1GB), and a few (20) megabytes have been used.

You can disable swap using the swapoff command, for example:

Important Note:If your swap space is being heavily used, it is probably affecting the performance of your application. Also, with an EBS volume, you will be incurring a cost for every I/O operation. There is nothing wrong with swapping out pages, as long as it isn’t occurring too frequently. You can configure the ‘swappiness’ of your system, by echoing out a value from 0 to 100 into /proc/sys/vm/swappiness. Low numbers reduce the system’s tendency to swap. One view point is that the lower numbers increase perceived responsiveness for a desktop, but higher numbers allow memory to be best used on a server environment.

Leave a Reply

Your email address will not be published.

Contact Us

Have a question? Send us a message. We'll get back to you soon.