How to Create a Swap File on Ubuntu 22.04

Jan 30, 2023

To create a swap file on Ubuntu 22.04, follow these steps:

Step 1 : Use the following command to check the available disk space:

df -h

Step 2 : Use the following command to create a swap file of the desired size. For example, to create a 2 GB swap file, you can use the following command:

sudo fallocate -l 2G /swapfile

Step 3 :Use the following command to change the permissions of the swap file:

sudo chmod 600 /swapfile

Step 4 :Use the following command to mark the file as a swap file:

sudo mkswap /swapfile

Step 5 :Use the following command to enable the swap file:

sudo swapon /swapfile

Step 6 :Verify that the swap file is enabled using the following command:

sudo swapon --show

Step 7 :To make the swap file persistent across reboots, add the following line to the /etc/fstab file:

/swapfile none swap sw 0 0

The recommended size for a swap file is equal to the amount of RAM in the system, or 2-4 GB. However, the actual size depends on the specific use case and the amount of memory in the system.