How to create a swap file for Ubuntu


Here are bare minimal instructions on how to set up a swap file for Ubuntu Linux.

In the beginning and in the end swapon command is used to test for the availability of the swap file. In the middle the vi text editor is used to append the requisite swap entries to fstab. If you’re working with AWS EC2, also see the reference pointing to their site.

Instructions (if you don’t have one)

sudo swapon --show

sudo fallocate -l 1G /swapfile

sudo chmod 600 /swapfile

sudo mkswap /swapfile

sudo swapon /swapfile

sudo vi /etc/fstab

Append /swapfile swap swap defaults 0 0

sudo swapon --show

free -h

Instructions (if you already have one)

There is a command swapoff

but the problem is you shouldn’t just use it unless you have a lot of time. See references why this is complicated, but in a nutshell once you run this command it’s going to transfer what’s in the current swap file to memory, and that’s a complicated process.

So it’s better just to create a new swap file, and then remove the other swap file later. Follow the above steps but use /swapfile2 as the name.


  1. https://linuxize.com/post/how-to-add-swap-space-on-ubuntu-18-04/
  2. https://aws.amazon.com/premiumsupport/knowledge-center/ec2-memory-swap-file/
  3. https://unix.stackexchange.com/questions/403451/why-is-swapoff-so-slow

Share this article

Share on facebook
Share on twitter
Share on linkedin

Leave a Reply

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

Scroll to Top