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.

It’s possible to use this entire procedure for CentOS 7 but you can’t do fallocate and you have to use dd instead. See the reference.

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.

How Much Swap Is Needed*

*Adapted from the Ubuntu reference, removed hibernation column as Server don’t hybernate

RAM       Recommended    Maximum
1GB          1GB          2GB
2GB          1GB          4GB
3GB          2GB          6GB
4GB          2GB          8GB
5GB          2GB          10GB
6GB          2GB          12GB
8GB          3GB          16GB
12GB         3GB          24GB
16GB         4GB          32GB
24GB         5GB          48GB
32GB         6GB          64GB
64GB         8GB          128GB
128GB        11GB         256GB
256GB        16GB         512GB
512GB        23GB         1TB
1TB          32GB         2TB
2TB          46GB         4TB
4TB          64GB         8TB
8TB          91GB         16TB


  1. https://help.ubuntu.com/community/SwapFaq#How_much_swap_do_I_need.3F
  2. https://linuxize.com/post/how-to-add-swap-space-on-centos-7/
  3. https://linuxize.com/post/how-to-add-swap-space-on-ubuntu-18-04/
  4. https://aws.amazon.com/premiumsupport/knowledge-center/ec2-memory-swap-file/
  5. 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