How to Create Linux Swap File

How to Create Linux Swap File



Swap space can take the form of either a dedicated swap partition or a swap file. In most cases, when running Linux on a virtual machine, a swap partition is not present, so the only option is to create a swap file.

This tutorial was tested on Linux systems with Ubuntu 18.04 and CentOS 7, but it should work with any other Linux distribution.

How to add Swap File

Follow these steps to add 1GB of swap to your server. If you want to add 2GB instead of 1 GB, replace 1G with 2G.

  1. Create a file that will be used for swap:
$ sudo fallocate -l 1G /swapfile

If faillocate is not installed or if you get an error message saying fallocate failed: Operation not supported then you can use the following command to create the swap file:


Only the root user should be able to write and read the swap file. To set the correct permissions type:

$ sudo chmod 600 /swapfile

Use the mkswap utility to set up the file as Linux swap area

$ sudo mkswap /swapfile

Enable the swap with the following command:

$ sudo swapon /swapfile

To make the change permanent open the /etc/fstab file and append the following line:


/swapfile swap swap defaults 0 0

To verify that the swap is active, use either the swapon or the free command as shown below:

$ sudo swapon --show
/swapfile file 1024M 507.4M   -1
$ sudo free -h
total        used        free      shared  buff/cache   available
Mem:           488M        158M         83M        2.3M        246M        217M
Swap:          1.0G        506M        517M

How to adjust the swappiness value

Swappiness is a Linux kernel property that defines how often the system will use the swap space. Swappiness can have a value between 0 and 100. A low value will make the kernel to try to avoid swapping whenever possible, while a higher value will make the kernel to use the swap space more aggressively.


$ cat /proc/sys/vm/swappiness

For example, to set the swappiness value to 10, you would run the following sysctl command:

$ sudo sysctl vm.swappiness=10




How to remove Swap File

If for any reason you want to deactivate and remove the swap file, follow these steps:

  1. First, deactivate the swap by typing:
$ sudo swapoff -v /swapfile


Finally, delete the actual swapfile file using the rm command:

$ sudo rm /swapfile


You have learned how to create a swap file and activate and configure swap space on your Linux system.
