create swap partition on ubuntu 204
How to create swap partition on Ubuntu 20.04 Mayur Chavhan

How to create Swap Partition on Ubuntu 20.04 and Debian 10

Mayur Chavhan Tutorials

Table of Contents

On AWS, If you are using smaller instance type like t2.small and t3.small or any Digital Ocean instance you are using which requires more RAM resources then you know it won't be enough for your application and it's application performance will take hit.

swap file system An Incredibly Easy Method That Works faster

Since, We have SSD / NVMe Storage solutions which are very fast can be use as an alternative to operate as a RAM so we can create a SWAP partition which is basically tells Operating System to store CPU operation data on the disk partition when RAM space is not sufficient but SWAP partition is not fast as traditional RAM but it gets the job done with very little work.

This article specifically made to help you to enable SWAP Partition to mount on the system for your instance or VPS.  Any Ubuntu or Debian based Linux operating system has same commands to set SWAP partition so you this guide will be useful for any debian based OS also for Ubuntu Desktop Users as well.

Create a File

Consider, You got an instance or VPS of 2 vCore and 2 GB RAM.

Use below command to create a 1 GB of Swap,

$ sudo dd if=/dev/zero of=/var/swapfile bs=1M count=1024

Above command will create a file "swapfile" in "/var" folder, but also learn what's the command actually doing,

bs=1M count=1024 will create 1GB "swapfile", so you can change count if you want to use count as 2048, 4096 for 2GB and 4GB respectively.

Alternative, Similar command you can use to create swapfile , 

$ sudo fallocate -l 1G /var/swapfile

Convert file into SWAP compatible file.

Now, Let's convert this file into an actual swap,

$ sudo mkswap /var/swapfile

We almost done,

Mount SWAP File

$ sudo swapon /var/swapfile

Now we are done, We have mounted an swapfile into swap partition so CPU will use it if RAM storage is nearly full.

You can check if swap partition properly mounted or not by using below command,

$ sudo swapon --show

aws-swapfile-ubuntu

Add SWAP at system boot entry.

At times, When VPS or instance will get rebooted or at system boot, Swap partition will get unmounted if it's entry not added in system boot entry.

Just add an entry to "/etc/fstab" file, Which System check if any partition needs to be mounted at boot.

$ echo "/var/swapfile swap swap defaults 0 0" | sudo tee -a /etc/fstab

That's it. You've just upgraded your server with a virtual RAM.

aws-swap-fstab

If you feel like a geek and really want to see summary of swap partition,

$ swapon --summary