By default, all Linux instances of EC2 come without swap. I’m not sure what the reasons for that are, BUT in a few situations it is important to have swap, instead of scaling up to an instance with more main memory. For instance, PHP Composer might break on an EC2 micro instance, due to the lack of available memory.
A very practical way of having swap is to create it in a file. This way, you don’t have to partition your EBS volume or add a new one. If you are using encrypted volumes and/or it is important to keep all data at rest encrypted, then create the swap file inside an encrypted volume.
Before executing this tutorial, back up all your data and/or take a snapshot of the machine.
To configure swap on a file, in a way that is persistent across reboots, do the following steps:
sudo -idd if=/dev/zero of=/opt/swap bs=1M count=1024. In this command we
are creating a file with 1GB (1024 blocks of 1MB). Change /opt/swap to the
desired pathmkswap /opt/swapchmod 600 /opt/swapswapon /opt/swap/etc/fstab
file to add the line /opt/swap swap swap defaults 0 0. It is important to
notice that the partition where the swap file is located must be configured
to mount on bootDone. Now, you can reboot your instance and your swap will still be working on the next boot.