Why and how you should add swap space to an Amazon EC2 instance

Image Description
Kobus Grobler

EC2 instances do not have swap enabled by default. But why would you need swap space in the first place, some would ask. Isn’t it slow?

Of course, but look at the alternative. When the system runs out of memory, the OOM killer will start killing processes - typically your web service because it uses the most memory. If, on the other hand, you have swap enabled, the system will just swap out some pages and things will get a bit slower. You might even enable a health check to send you a notification that you are starting to use swap space. Then you may want to start using a bigger instance or optimize your process. The point is it will give you time to act appropriately: swap is your safety net.

You could of course just use a bigger instance with lots more memory and use that as your safety net - but then cost becomes an issue.

So here goes:

  1. Create a 1GB swap file (/var/swap in this case):

     /bin/dd if=/dev/zero of=/var/swap bs=1M count=1024
  2. Make a swap file system:

     /sbin/mkswap /var/swap
  3. Set proper permissions:

     chmod 600 /var/swap
  4. And turn it on:

     /sbin/swapon /var/swap
  5. To enable swap on image restart, edit /etc/fstab and add the following line:

                 /var/swap   swap    swap defaults   0   0