Tutorial

How to Create a Swap File in Ubuntu to Increase Memory - Step-by-step Guide

In this step-by-step tutorial, we show you how to create a swap file in Ubuntu to increase the memory. This is useful when the physical memory of the system is not enough to run all the running applications and processes. We show you how to create an empty swap file, set permissions, mark it as a swap area, enable it, and add it to the /etc/fstab file to ensure it is automatically enabled on system restart. This tutorial is suitable for users with root access or sudo privileges.

Prerequisites

  • Ubuntu operating system
  • Root access or sudo privileges

Step 1: Check if a swap file already exists

Run one of the following commands to check if a swap file already exists:

sudo swapon --show

Oder:

cat /proc/swaps

Step 2: Create an empty swap file

If no swap file exists, create an empty file using the command:

sudo fallocate -l 1G /swapfile

This creates a 1 GB swap file named swapfile in the root directory. You can specify a different size by adjusting the value of 1G accordingly.

Step 3: Set the permissions of the swap file

Set the permissions of the swap file using the command:

sudo chmod 600 /swapfile

Step 4: Mark the swap file as a swap area

Mark the swap file as a swap area using the command:

sudo mkswap /swapfile

Step 5: Enable the swap file

Enable the swap file using the command:

sudo swapon /swapfile

Step 6: Add the swap file to the /etc/fstab file

To ensure that the swap file is automatically enabled on system restart, add it to the /etc/fstab file using the command:

sudo bash -c "echo '/swapfile none swap sw 0 0' >> /etc/fstab"

Step 7: Done!

The memory should now be successfully increased. You can check the current swap status using the free -h command.

In this tutorial, you learned how to create a swap file in Ubuntu to increase the memory. A swap file is a useful way to increase the memory of the system by moving parts of the memory to the hard drive. It is important to note that using swap files can affect the performance of the system, as access to the hard drive is slower than access to memory. Therefore, you should only use swap files when they are actually needed.