DEV Community

Cover image for Allocate swap memory to Ec2 linux instance or any other linux machine
Surya Shankar
Surya Shankar

Posted on • Edited on

Allocate swap memory to Ec2 linux instance or any other linux machine

- If you ever heard of the virtual memory, then in case of linux machines you are looking at swap memory.
- Swap space is the dedicated space from your hard disks or SSDs that is used when you Physical RAM is full.
- If the operating system is in need of more memory resources and the its RAM is full, inactive pages in memory are moved to the swap space. By inactive pages we mean the content that is not needed on urgent basis or not in use.

Before you start creating a swap file, you should check your Ubuntu system if it contains an existing swap file, use the command below to verify:

swapon --show
Enter fullscreen mode Exit fullscreen mode

If output is empty, then you can create a new Swap file. Otherwise, If swap file is exist, then you can turn it on or else upgrade the size.

You can also run free command to check the memory information.

free -h
Enter fullscreen mode Exit fullscreen mode

Image description

How to attach a swap memory

We can attach it to our server disk.
Suppose we have a disk attached to our server called sdc as shown

Image description

fdisk /dev/sdc
Enter fullscreen mode Exit fullscreen mode

Image description

Type m for help
Enter fullscreen mode Exit fullscreen mode

Image description

Type 'n' :- To add a new partition
Enter fullscreen mode Exit fullscreen mode
Select 'p' for default
Enter fullscreen mode Exit fullscreen mode

Enter partition number (1-4):1

Set the last sector partition size to 5G as shown below

Image description

Type 'p' to print partition table
Enter fullscreen mode Exit fullscreen mode

Image description

Type 'l' to list know partition type
Enter fullscreen mode Exit fullscreen mode

As you can see the swap id hex code is 82

Image description

Type 't' to change the partition
Enter fullscreen mode Exit fullscreen mode

Enter Hex code as 82

Image description

We have successfully change the partition , Type 'p' to print the Partition.

Type 'w' to save and exit
Enter fullscreen mode Exit fullscreen mode

Image description

partprobe is a program that informs the operating system kernel of partition table changes, by requesting that the operating system re-read the partition table.

partprobe /dev/sdc1
Enter fullscreen mode Exit fullscreen mode

Image description

Now use the mkswap command to setup a Swap area

Image description

Using swapon command, we can use the newly created space for immediate use

Image description

You can now run free command to check the memory information.

free -h
Enter fullscreen mode Exit fullscreen mode

Image description

Update the /etc/fstab file to use it at boot time only

Image description

Verify the newly created swap

Image description

Top comments (0)