To add swap to an AWS EC2 or Lightsail Amazon Linux instance, you will need to follow these steps:
Connect to the instance using SSH.
Check if the instance already has a swap partition by running the swapon command. If the command returns output, it means the instance already has a swap partition and you don't need to create a new one.
If the instance doesn't have a swap partition, create a new swap file with the dd command. For example, to create a 1 GB swap file, you can use the following command:
dd if=/dev/zero of=/swapfile bs=1M count=1024
This will create a new file named /swapfile containing 1 GB of zeroed data.
chmod command:chmod 600 /swapfile
mkswap command to create a swap partition from the swap file:mkswap /swapfile
swapon command:swapon /swapfile
/etc/fstab file. Open the file with a text editor, such as nano or vi, and add the following line at the end:/swapfile swap swap defaults 0 0
Save the file and exit the editor.
free -m command. The output should show the swap partition being used.Note: You can specify a different size for the swap file by changing the
countvalue in theddcommand. For example, to create a 2 GB swap file, you can usecount=2048. It is recommended to set the swap size to at least twice the amount of physical RAM on the instance.