How To Create SWAP Partition in EC2 Instance

Check if the system has any configured swap.

$ sudo swapon –show

If you get the output that means you already have a configured swap memory. For example.

NAME          TYPE        SIZE    USED  PRIO
/dev/sda5   partition   8G   0B        -1

If you don’t get any output means your system does not have a swap memory.

To create a swap memory follow these instructions:

Verify is there any swap memory or not?

$ free -h
                     total        used        free      shared  buff/cache   available
Mem:           5.3G        1.2G        2.4G         46M        1.7G        3.7G
Swap:          0G            0B           0G

No swap memory is active If the Swap section is zero.

Check the system usages.

$ df -h
Filesystem      Size       Used Avail Use% Mounted on
udev                  2.7G     0  2.7G   0% /dev
tmpfs               544M    8.2M  536M   2% /run
/dev/sda1       184G     87G   88G  50% /
tmpfs               2.7G      7.7M  2.7G   1% /dev/shm
tmpfs               5.0M     4.0K  5.0M   1% /run/lock
tmpfs               2.7G      0  2.7G   0% /sys/fs/cgroup
cgmfs              100K     0  100K   0% /run/cgmanager/fs
tmpfs               544M    36K  544M   1% /run/user/1000

In /dev/sda1 section the system has 184GB storage where 88GB is free. We have plenty of space for swap memory.

Create swap memory by allocating a space from storage:

$ sudo fallocate -l 1G /swapfile

Here I’m creating 1GB of swap memory. You can adjust it depending of the requirements.

Verify the space is allocated or not.

$ ls -lh /swapfile

Change the permission of swap memory to 600 so it can only accessible by root.

$ sudo chmod 600 /swapfile

mark the allocated space to be use use as a swap memory.

$ sudo mkswap /swapfile

Enable the swap space.

$ sudo swapon /swapfile

This space we allocated is currently temperory. After reboot it will deallocat the space.

So we have to make it permanent.

echo ‘/swapfile none swap sw 0 0’ | sudo tee -a /etc/fstab

And finally reboot the instance.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *