How to create or increase the size of swap space in Ubuntu

Reading Time: 2 minutes

One of the use case for swap space is the hibernate utility. If you haven’t allocated swap space or the space allocated is less than your RAM, your system will not hibernate. To fix this, you need to create a swap space large enough to hold a copy of your RAM. I will tell you in simple steps how to create or increase the size of swap space. This should work in most of the linux systems, but I have tested this on Ubuntu 20.04.

1. Create a new swap space

First of all you need to create a swap file. See the command below which creates a swapfile of size 1GB

sudo fallocate -l 1G /swapfile

You should also set the permission of this file to root user. This is optional, but recommended.

sudo chmod 600 /swapfile

2. Increase the size of existing swap space

Turn off all swap processes

sudo swapoff -a

resize the file using command below. In this, /dev/zero is the location of existing swap file. We are changing the size to 8GB as 8 chunks (count=8) of size 1GB each (bs=1G)

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

Now, make the newly created swap file or the updated swap file to be usable as swap space

sudo mkswap /swapfile

Activate the swap space

sudo swapon /swapfile

Voila ! It’s done. You can verify this by using this command

sudo swapon --show

If everything was successful, you should see an output like this

ankit@ankit-linux:~$ sudo swapon --show
[sudo] password for ankit: 
NAME      TYPE SIZE  USED PRIO
/swapfile file   8G 13.2M   -2

Leave a Reply