How do you add swap to an EC2 instance

Paging works by creating an area on your hard drive and using it for extra memory, this memory is much slower than normal memory however this is much more of it available.

To add this extra space to your instance you type:

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

If you need more than 1024 then change that to something higher.

To enable it by default after reboot, add this line to /etc/fstab:

/var/swap.1 swap swap defaults 0 0


For Example: Use 16GB SSD for Swap on Amazon Linux c3.large Instance


Testing the SSD speed

Once set up and server launched, we can use 2nd 16GB SSD (mounted on /dev/sdc) for swap on new Amazon Linux instance c3.large 
# Test SSD disk speed
cd /media/ephemeral0/
sudo /bin/dd if=/dev/zero of=outfile.tmp bs=1M count=2048

2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB) copied, 4.61377 s, 465 MB/s

# Test EBS speed on c3.large
cd ~
sudo /bin/dd if=/dev/zero of=outfile.tmp bs=1M count=2048

2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB) copied, 70.5714 s, 30.4 MB/s

Setting up swap (and flooding it)

You can see that those 2 x 16GB SSD onboard of c3.large are snappy and fast. Now, let's set up swap to be mounted on 16GB SSD /dev/xvdc
# Utilize 2.nd 16GB SSD for Swap on c3.large
sudo mkswap /dev/xvdc
sudo swapon /dev/xvdc
echo "/dev/xvdc swap swap defaults 0 0" | sudo tee -a /etc/fstab
 
  • 17 Users Found This Useful
Was this answer helpful?