Tutorial

Step-by-step guide to creating a swap file in an EC2 instance - Step-by-step Guide

In this article, you will learn how to create and enable a swap file in an EC2 instance running Ubuntu to extend the memory. We will go step by step through the process and also show you how to automatically enable the swap file on system startup. This is particularly useful if you have an instance with low memory and need more resources.

Prerequisites

  • An EC2 instance running Ubuntu 18.04 or higher
  • SSH access to the instance
  • Root access or sudo privileges

Step 1: Create the swap file

First, we need to create a swap file. This will be used to extend the memory by acting as additional virtual memory.

Run the following command to create a 1 GB swap file:

sudo fallocate -l 1G /swapfile

This will create a 1 GB empty file named /swapfile. You can create a larger or smaller swap file by adjusting the value of 1G accordingly.

Step 2: Set permissions for the swap file

Next, we need to set the permissions for the swap file to ensure that only the root user can access it. Run the following command to do this:

sudo chmod 600 /swapfile

Step 3: Format the swap file

Before we can use the swap file, we need to format it. Run the following command to do this:

sudo mkswap /swapfile

This will format the swap file and prepare it for use as swap memory.

Step 4: Enable the swap file

Now we can enable the swap file by running the following command:

sudo swapon /swapfile

The swap file is now enabled and will be used to extend the memory.

Step 5: Automatically enable the swap file on system startup

To ensure that the swap file is automatically enabled on system startup, we need to add it to the /etc/fstab file. Open the file with the following command:

sudo nano /etc/fstab

Add the following line at the end of the file:

/swapfile swap swap defaults 0 0

Save the file and close the text editor. The swap file will now be automatically enabled on system startup.

To verify that the swap file was correctly enabled, run the following command:

free -h

This will show you the current memory status and should also display the additional swap memory.

In this step-by-step guide, we learned how to create and enable a swap file in an EC2 instance running Ubuntu to extend the memory. We created the swap file, set the permissions, formatted it, and finally enabled it. We also learned how to automatically enable the swap file on system startup by adding it to the /etc/fstab file.