Add SWAP disk on Amazon EC2 Ubuntu servers

Scenario

My Ubuntu web servers were killing processes due to low free memory. I would prefer them to slow down than to kill processes. So I added SWAP disk space that is not setup by default in the EC2 instances.

Prerequisites

Amazon AWS EC2 Ubuntu 11 or 12 instance.

This may work on other Linux versions, but I have only used it on Ubuntu.

Process

Briefly, the process is to create a storage volume in the same zone as the Ubuntu instance.
Attach the disk to the instance making note of the device identity. I picked /dev/sdm (m for memory).
Then as root, or sudo, format the swap space.
Update the /etc/fstab file.
Activate the swap space.

The Ubuntu Linux commands follow:

See if there is any swap space already.

free -m 
swapon -s

CAREFUL HERE. Ubuntu uses a different identifier than Amazon. Look for the volume here.

fdisk -l

CAREFUL HERE. Format the new volume for swap.

mkswap /dev/xvdm

Set the Swap disk to mount on boot by adding a line to /etc/fstab

/dev/xvdm   none   swap  sw 0 0

(https://help.ubuntu.com/community/Fstab)

Activate the swap space.

swapon -a

Verify swap space.

swapon -s
free -m 

Alternate Process to create Swap File not Disk

The Ubuntu Linux commands follow:

See if there is any swap space already.

free -m 
swapon -s

Create a file to use for swap.

fallocate -l 2048m /mnt/swapfile.sys

Set the permissions for the new swap file.

chmod 600 /mnt/swapfile.sys

Set the Swap disk to mount on boot by adding a line to /etc/fstab

/mnt/swapfile.sys   none   swap  sw 0 0

(https://help.ubuntu.com/community/Fstab)

Activate the swap space.

swapon -a

Verify swap space.

swapon -s
free -m