Adding swap space to an EC2 Amazon Linux instance

Adding swap space to an EC2 Amazon Linux instance

I run all my websites on a tiny Amazon EC2 t2.nano instance, which has 512MB of RAM. This runs Nginx, MySQL, PHP, Monit, and other bits and pieces. The instance is easily powerful enough for most tasks, especially given I use a the CloudFlare Content Distribution Network (CDN).

The instance occasionally runs out of memory when I do a “yum update”, so I decided to add some swap space. Hit “read more” to see how I did this.

My t2.nano has 3.4GB free, and because I sometimes need available disk space for various tasks I decided I only wanted to use 512MB of disk as swap. That should give the system enough space for running yum updates without having to shut PHP down, which I’ve been doing for the past couple of months.

Note that I’m putting my swap onto EBS disk, which is a network disk. This instance gets 76MB/sec of throughput to EBS, which is much lower than a local disk would get, but hey it’s what the instance has. The operating system (Amazon Linux) knows that swap is slow, so it won’t put anything it needs fast access to in there.

AWS also recently announced you can resize your EBS volumes, a really handy feature.

Here’s my free memory before I started this process

                  total used free shared buffers cached
Mem:                491  460   30    164      30    228
-/+ buffers/cache:       202  289
Swap:                 0    0    0


Here’s the free memory after

                   total used free shared buffers cached
Mem:                 491  485    5    122      21    323
-/+ buffers/cache:        140  350
Swap:                511    0  511

Here are the steps I took to enable swap space

dd if=/dev/zero of=/swapfile bs=1M count=512
mkswap /swapfile
chmod 600 /swapfile
swapon /swapfile

You also have to edit your fstab file so the swap is available after reboot

vi /etc/fstab

Add the following to the bottom of the file – I made sure it lined up with the existing entries, but that’s probably not necessary.

/swapfile swap swap defaults 0 0

That’s it! Start to finish it took me 15 minutes. It’s surprisingly easy to add swap to your Amazon Linux instance.

Facebook Comments

One thought on “Adding swap space to an EC2 Amazon Linux instance

Leave a Reply

Your email address will not be published. Required fields are marked *