How to Increase/Decrease Swap Disk Size on Linux (Swapfile method)

Linux

Checking the Current Swap Disk Size and Swapfile Location

You can check the current swap disk size with the following command:

$ sudo swapon --show

As you can see, currently my computer has 512MB of swap disk space configured. It’s using a file-based swap and the swap file path is /swapfile.

Disabling the Current Swap

To make changes to the current swap configuration, you must disable the current swap.

In this case, we are using a swapfile with the path /swapfile. To disable /swapfile, use the following command:

$ sudo swapoff /swapfile

Creating a New Swapfile

To create a new 16GB swapfile (let’s say), run the following command:

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

As you can see, a 16GB swapfile /swapfile is created.

Formatting the Swapfile

To format the newly created /swapfile, run the following command:

$ sudo mkswap /swapfile

The /swapfile should be readable and writeable by only the root user. To change the file permission, run the following command:

$ sudo chmod 0600 /swapfile

Enabling the New Swap

To enable the newly created /swapfile as swap, run the following command:

$ sudo swapon /swapfile

To check the current swap size, run the following command:

$ sudo swapon --show

The swap size should be changed to 16GB as you can see in the screenshot below.

Adding the Swapfile to /etc/fstab

If you don’t have a swapfile already configured on your computer, then follow all the methods above and add the swapfile to /etc/fstab so that it’s automatically mounted on system reboot.

First, open the /etc/fstab file with the following command:

$ sudo nano /etc/fstab

Add the following line at the end of the /etc/fstab file and save the file by pressing <Ctrl> + X followed by Y and <Enter>.

/swapfile swap swap defaults 0 0

Related Posts

Leave a Reply

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