Create Swap File – Ubuntu Linux

Swap in Linux is a space on a disk drive (HDD or SSD) that is used when the amount of physical memory (RAM) tends to get full.

Swap space is usually created as a dedicated swap partition during the system’s installation but it also can take the form of a swap file.

As usually there is no swap partitions on Linux VMs, the only way to create or extend a swap space there is by creating a swap file.

In this note i will show how to create a swap file on Ubuntu, though these commands should work for the other Linux systems as well.

Cool Tip: How to change swappiness (swap usage tendancy)! Read more →

Create Swap File

Display the current swap usage and list all swap devices and files:

$ free -h
$ cat /proc/swaps

Create a swap file with the secure permissions:

$ sudo install -o root -g root -m 0600 /dev/null /swapfile

Use one of the commands below to set the swap file size to 1GB:

$ sudo fallocate -l 1G /swapfile
- or -
$ dd if=/dev/zero of=/swapfile bs=1k count=1024k

Set up a Linux swap area in the /swapfile:

$ sudo mkswap /swapfile

Add the /swapfile to the system’s swap space:

$ sudo swapon /swapfile

Add the /swapfile swap swap defaults 0 0 to the end of /etc/fstab to make the change permanent:

$ sudo echo "/swapfile swap swap defaults 0 0" | sudo tee -a /etc/fstab

Verify that the system’s swap space has successfully been extended:

$ free -h
$ cat /proc/swaps

Cool Tip: How to disable swap in Linux! Read more →

Was it useful? Share this post with the world!

Leave a Reply