DEV Community

Hardik Sondagar
Hardik Sondagar

Posted on


How to use AWS EBS volume as a swap memory

What is swap space?

Swap space in Linux can be used when a system requires more memory than it has been physically allocated (RAM). When swap space is enabled, Linux systems can swap infrequently used memory pages from physical memory to swap space (either a dedicated partition or a swap file in an existing file system) and free up that space for memory pages that require high-speed access. [1]

Step 1 - Create EBS Volume

Follow steps to create EBS Volume in AWS Console, that we'll use as a swap memory.

  1. Go to EC2 Dashboard
  2. Select EBS Volumes
  3. Create Volume
  4. Recommended size of swap volume is 2 times of RAM [2]
  5. Select availability zone same as your EC2 instance

Step 2 - Attach EBS Volume to EC2

Select EBS Volume that we just created for swap and your EC2 instance.

Step 3 - Set EBS Volume as swap space

Run lsblk to check new volume, it will appear as /dev/xvdf on instance.

$ lsblk
xvda    202:0    0  256G  0 disk
└─xvda1 202:1    0  256G  0 part /
xvdf    202:80   0   32G  0 disk
Enter fullscreen mode Exit fullscreen mode

Set up the swap area

$ sudo mkswap /dev/xvdf
Enter fullscreen mode Exit fullscreen mode

Enable swap

$ sudo swapon /dev/xvdf
Enter fullscreen mode Exit fullscreen mode

Make this swap setting persist by adding following line in /etc/fstab

$ sudo nano /etc/fstab
/dev/xvdf none swap sw 0 0
Enter fullscreen mode Exit fullscreen mode

Step 4 - Check swap space

$ sudo swapon --show
/dev/xvdf partition  32G 279.9M   -1
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

kkdg profile image
Degi Kwag

Master of guide

ferricoxide profile image
Thomas H Jones II

Similarly, if you've deployed your instance on a elastic EBS volume, you can grow the volume and add a partition to the EBS ...that you can swap to.

siddhinathk profile image
Siddhinath Kharade

Thanks For Blog

rinzler profile image

What a simple, yet great post. As an AWS user, I'll try this ASAP on one of my test instances.

nayak015 profile image
Ankit Nayak

Thank you! Great post!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.