How to add swap memory on AWS/EC2 linux instance

DATE : 29-04-2020

Hello!! Let us know how to enable swap file system. There are two methods of adding swap memory in aws ec2 instance.

INTRODUCTION:

Swap memory is useful for systems having memory issue due to less memory. If your system facing the problem of lack of memory continuously and you don’t want to increase memory on the server, Then it can be helpful to enable swap in your system. Swap memory occupies much lower space than physical memory.

METHOD 1: Using swap file

This method is helpful if we don’t want to add extra disks in our systems.

In this method, we can create a file in our current file system and make it type swap, which can be used as swap in our system.

Use the below commands to create and enable swap on our system.

$ sudo dd if=/dev/zero of=/var/myswap bs=1M count=2048
$ sudo mkswap /var/myswap
$sudo swapon /var/myswap

Here, we have created bs=1M count=2048 means 2GB of swap file. After enabling swap we can see that our system has swap enabled by running “free -m” command.

To make it enable on system boot, simply edit /etc/fstab file and add below mentioned entry at the end of the line.

/var/myswap swap swap defaults 0 0

After adding, save and close the file.

METHOD 2: Using Additional Disk for Swap

This option is helpful if you do not have enough space in our current drives mounted in the system. In this option, first, we need to add extra disk in our system first. In my case new disk mounted as /dev/xvdd.

$sudo mkswap -f /dev/xvdd
$sudo swapon /dev/xvdd

To make it enable on system boot, simply edit /etc/fstab file and add following entry at end of the line.

/dev/xvdd swap swap defaults 0 0

After adding, save and close the file.

Thank you.

Leave a Reply