Get in touch
or send us a question?

How do you add swap to an EC2 instance

To create a swap file on an EC2 instance running a Linux-based operating system, you can follow these general steps:

Step1: Connect to your EC2 instance using SSH.
Step2: Check the current swap usage on the instance using the free -h command. This will show you if you already have a swap file or partition configured on the system.

Step3: Determine how much swap space you need by considering the amount of available memory and the applications you plan to run. A good rule of thumb is to allocate twice the amount of available RAM, up to a maximum of 4GB.

Step4: Create a swap file using the dd command, specifying the desired size and location of the file. For example, to create a 4GB swap file called swapfile in the root directory, you could use the following command:

sudo dd if=/dev/zero of=/swapfile bs=1G count=4

Note that the bs argument specifies the block size (in this case, 1GB) and the count argument specifies the number of blocks to create.

Set the correct permissions on the swap file using the chmod command:

sudo chmod 600 /swapfile

This ensures that only the root user can read and write to the file.

Set up the swap space using the mkswap command:

sudo mkswap /swapfile

Activate the swap space using the swapon command:

sudo swapon /swapfile

This will immediately activate the swap space and start using it.

To make the swap file permanent across reboots, you can add an entry to the /etc/fstab file:
/swapfile none swap sw 0 0
This will cause the swap file to be automatically mounted and activated during boot.