How to configure swap for your EC2 instance

Swap

Every time I fire up a new EC2 instance, I inevitably forget to configure swap memory for it (why don’t they just come pre-configured?) only to realize it later when some application experiences sudden death at the hands of a (shriek!) OutOfMemoryError. I’ve gotten pretty quick at configuring this, and thought I’d share the recipe.

The following instructions are for an EC2 instance running Amazon Linux (which is basically CentOS). They will probably work for any RedHat-based distro.

First of all, check to see if you already have swap configured:

<br /> $ free<br /> total used free shared buffers cached<br /> Mem: 7697592 7653364 44228 260 988 88732<br /> -/+ buffers/cache: 7563644 133948<br /> Swap: 0 0 0<br />

If the “Swap” section is 0, then you obviously do not and you will need to configure it.

Depending on your instance type, you may or may not have “instance storage” (also called “ephemeral storage”). If you do, this is an ideal place to have your swap space because it’s fast, “close” to your OS and it gets obliterated if you ever need to stop your instance (so it’s only good for transient data anyways).

If you have instance storage available, it should be visible as a storage device in addition to any EBS volumes you have attached:

<br /> $ ls /dev/sd*<br /> /dev/sda1 /dev/sdb /dev/sdc<br />

(in this case, sda1 is my root (OS) volume, sdb is my data (EBS) volume, and sdc is my instance storage (swap).

If you do have instance storage and wish to use it as a swap partition,

<br /> mkswap /dev/sdc<br /> swapon -va<br />

If you do not have instance storage (or don’t want to use the whole thing for swap), you’ll need to create a swap file instead:

<br /> dd if=/dev/zero of=/var/swapfile bs=1M count=2048<br /> chmod 0600 /var/swapfile<br /> mkswap /var/swapfile<br /> swapon -va<br />

(this means 2048 blocks @ 1Mb/block = 2Gb)

Then to make sure your swap gets turned on again after reboot, add a line to your /etc/fstab:

/dev/sdc none swap sw 0 0

or

/var/swapfile none swap sw 0 0

To verify that your swap is now indeed available:

<br /> $ free<br /> total used free shared buffers cached<br /> Mem: 7697592 7653364 44228 260 988 88732<br /> -/+ buffers/cache: 7563644 133948<br /> Swap: 30712 617 30095<br />

In case this didn’t do the trick, here are the official instructions from Amazon.

Written on February 22, 2015