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:
Create a 1GB swap file (/var/swap in this case):
/bin/dd if=/dev/zero of=/var/swap bs=1M count=1024
Make a swap file system:
Set proper permissions:
chmod 600 /var/swap
And turn it on:
To enable swap on image restart, edit /etc/fstab and add the following line:
/var/swap swap swap defaults 0 0