How to add swap to AWS EC2/Lightsail Amazon Linux instance
Amazon EC2/Lightsail Amazon Linux instances do not come with swap configured. However, you can easily create a swap file on these instances, to give the system extra memory. Here are the steps to add swap to an AWS EC2/Lightsail Amazon Linux instance:
Step 1: Create Swap File
The first step is to create a swap file. You can do this with the following command:
sudo dd if=/dev/zero of=/var/swapfile bs=1K count=1024
This will create a 1GB swap file. You can create a larger swap file if desired.
Step 2: Format Swap File
Once the swap file is created, you need to format it for use as swap. This can be done with the following command:
sudo mkswap /var/swapfile
Step 3: Activate Swap File
Now the swap file is ready to use. You must now activate it with the following command:
sudo swapon /var/swapfile
Step 4: Add Swap File to Fstab
Once the swap file is activated, it must be added to the `/etc/fstab` file so that it will be enabled at every boot. To do this, use the following command:
sudo bash -c "echo '/var/swapfile swap swap defaults 0 0' >> /etc/fstab
Step 5: Adjust Swap File Permissions
Finally, the swap file permissions must be adjusted with the following command:
sudo chmod 600 /var/swapfile
This will complete the process of adding swap to an AWS EC2/Lightsail Amazon Linux instance. Make sure to check the swap usage periodically to ensure it is not overused.
Tip: If you need to remove swap from the instance, you can do so with the following command:
sudo swapoff -v /var/swapfile
In this post we learnt how to add swap to AWS EC2/Lightsail Amazon Linux instance as by default swap is not enable in EC2 instance.