How to add swap to AWS EC2/Lightsail Amazon Linux instance

How to add swap to AWS EC2/Lightsail Amazon Linux instance

To add swap to an AWS EC2 or Lightsail Amazon Linux instance, you will need to follow these steps:

  1. Connect to the instance using SSH.

  2. 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.

  3. 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:

‮refer‬ to:lautturi.com
dd if=/dev/zero of=/swapfile bs=1M count=1024

This will create a new file named /swapfile containing 1 GB of zeroed data.

  1. Set the correct permissions on the swap file with the chmod command:
chmod 600 /swapfile
  1. Use the mkswap command to create a swap partition from the swap file:
mkswap /swapfile
  1. Enable the swap partition with the swapon command:
swapon /swapfile
  1. To make the swap partition permanent, you will need to add an entry to the /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.

  1. To check if the swap partition is working correctly, run the 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 count value in the dd command. For example, to create a 2 GB swap file, you can use count=2048. It is recommended to set the swap size to at least twice the amount of physical RAM on the instance.

Created Time:2017-10-28 21:38:58  Author:lautturi