Add Swap Space to EC2 Instances to Avoid Having to Upgrade to a Larger Instance

If you occasionally find that your EC2 instance runs out of memory & you don’t wanna upgrade to a larger instance, consider adding swap space (a.k.a. paging) to it!

Paging works by creating an area on your hard drive & using it for extra memory. This is much slower than normal memory but a lot more of it is available.

To create swap, run these at a terminal:

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

That creates 1G swap. Increase the 1024 above to get more.

if is “input file”, of is “output file”, bs is “block size” & count is the number of blocks you want to allocate. See dd‘s man page here.

That dd command says “copy from /dev/zero to /var/swap 1024 blocks of size 1 MB each”. It’s a quick way to create a 1 GB file full of zeroes.

To auto-enable swap on reboot, add this to /etc/fstab:

/var/swap    swap    swap    defaults    0    0

Run free -m or cat /proc/meminfo to see if the swap is active.

Swap space should be placed on ephemeral instance storage disk, not on an EBS volume. Swapping causes a lot of I/O & will increase EBS cost (only for provisioned IOPS volumes). EBS is also slower than instance store, introduces more latency & comes free with certain types of EC2 Instances.

To create swap on instance store:

sudo mount /dev/xvda2 /mnt
sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=4096
sudo chown root:root /mnt/swapfile
sudo chmod 600 /mnt/swapfile
sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile
sudo swapon -a

And in fstab:

/dev/xvda2      /mnt    auto    defaults,nobootwait,comment=cloudconfig 0   2
/mnt/swapfile swap swap defaults 0 0

Also see Instance store swap volumes & How do I allocate memory to work as swap space in an Amazon EC2 instance by using a swap file?.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.