How to create, remove and mount swap file on Ubuntu 17.04

Today we will learn how to create swap file on Ubuntu 17.04. Also we will learn how we can remove swap file and mount it on a Ubuntu 17.04. This tutorial can be used on any other Linux distribution as well. As you might know, the new Ubuntu 17.04 supports swap file which mean it does not require a dedicated swap partition for Ubuntu to work.

Check the current swap size

First, lets check the current swap size with the following command:

free -h
swapon --show

As you can see, my current system still uses /dev/sda5 partition as the swap. It is fine but next, we will create swap file and use it.

Create Swap file

I am going to create a new swap file 2048 MB in size. You may change it freely.

sudo fallocate -l 2048M /swapfile

The command above will create a new swap file with 2048 megabytes in size and save if as “swapfile” under “/” directory.

Now continue with these commands to make it active and usable. Make sure you run these as root or sudoer.

chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap defaults 0 0' >> /etc/fstab

Now check the swapfile status

dhani@dhani-budgie:~$ free -h
              total        used        free      shared  buff/cache   available
Mem:           3,8G        745M        2,2G        8,2M        817M        2,8G
Swap:          5,9G          0B        5,9G
dhani@dhani-budgie:~$ swapon --show
/dev/sda5 partition 3,9G   0B   -1
/swapfile file        2G   0B   -2

As you can see my new 2 GB swapfile has been activated.

How to remove Swapfile

In case you want to remove or delete existing swapfile, do the following:

Remove or comment the swapfile entry on /etc/fstab

# /etc/fstab: static file system information.
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda1 during installation
#UUID=a9934d96-33e6-4ee3-bb8a-eb4f949dd053 /               ext4    errors=remount-ro 0       1
# swap was on /dev/sda5 during installation
#UUID=62ef03bd-6b44-4983-aee3-0d42c1cdb166 none            swap    sw              0       0

Next execute these command as root, not sudo.

echo "3" > /proc/sys/vm/drop_caches
swapoff -a
rm -f /swapfile

Now check with swapon –show command. Now it should not returned anything since the swapfile has been removed and deactivated.


Leave a Reply

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