change ubuntu swap size

Back in the day, Ubuntu used to have a dedicated swap partition, and it was recommended to allocate 2x the installed RAM to this swap partition.

However, the swap partition has been superseded by a swap file since Ubuntu 18.04. Unless you hibernate your system, the swap size standards are also no longer relevant and most users can safely get by with 1-2 GBs of swap.

With these things in mind, we’ll cover the steps to change the swap size on modern Ubuntu versions like 22.04 in this article.

Check Current Swap Size

First of all, check the name and size of the currently active swap files. 

swapon --show

In my case, I currently have a 2 GB file named swapfile.

Disable/Delete Old Swapfile

We’ll delete the old swap file before creating a new one of the preferred size.

 sudo rm /swapfile

If this fails, you should create a new swap file first, then delete the old one. Alternatively, you can disable this swapfile and create a new one with a different name as that works too.

sudo swapoff /swapfile

Create New Swap File

Now, we’ll use dd to create a new swap file. We’re using a 1 MiB block size (bs) and specifying to copy 16384 blocks. This’ll result in a 16 GiB swap file.

sudo dd if=/dev/zero of=/swapfile bs=1M count=16384

If you want a different-sized swap file, all you need to do is adjust the bs or count. For instance, the following command creates a 1 GiB swap file instead.

sudo dd if=/dev/zero of=/swapfile bs=1G count=1

Set Up New Swap File

Simply creating a file named swapfile doesn’t actually set it up as the swap space. You have to use the mkswap command on it to do this.

sudo mkswap /swapfile

Now, set the permissions for this file so that only the root user can read from/write to it.

sudo chmod 0600 /swapfile

Needless to say, if you used a different filename for your swap file, change swapfile to the filename in all the commands.

Enable New Swap File

We’ll use the swapon command to enable the file we just created for paging and swapping. 

sudo swapon /swapfile

You can verify that the swapfile is active with

swapon --show

Since we created a new swap file, the changes made just now are only for the current session. To make the changes persistent, you must ensure the swapfile is included in the /etc/fstab file.

First, back up the original fstab file to account for any unintended changes.

sudo cp /etc/fstab /etc/fstab.bak

Now, append the swapfile entry to the fstab file.

sudo nano /etc/fstab
swapfile none swap sw 0 0
Anup Thapa

Senior Writer

Anup Thapa is a Linux enthusiast with an extensive background in computer hardware and networking. His goal is to effectively communicate technical concepts in a simplified form understandable by new Linux users. To this end, he mainly writes beginner-friendly tutorials and troubleshooting guides. Outside of work, he enjoys reading up on a range of topics, traveling, working out, and MOBAs.