To add swap to an Amazon Linux EC2 or Lightsail instance on AWS, you can use the following steps:
- Connect to your instance via SSH.
- Check if there is any existing swap partition by running the command
sudo swapon --show
- If there is no existing swap partition, create a new one by running the command
sudo fallocate -l <size> /swapfile
where<size>
is the size of the swap partition you want to create. For example, to create a 4GB swap partition, you would runsudo fallocate -l 4G /swapfile
- Change the permissions of the swap file to 600:
sudo chmod 600 /swapfile
- Mark the file as swap space:
sudo mkswap /swapfile
- Enable the swap file:
sudo swapon /swapfile
- Make the swap partition persistent across reboots, by adding the following line to
/etc/fstab
/swapfile swap swap defaults 0 0
- You can check the swap status by running
free -h
Please note that you should use the appropriate size for your specific use case, and also that swap usage can impact your performance, so monitor the usage and adjust accordingly.