Links: https://help.ubuntu.com/community/SwapFaq

Steps to create a swapfile

Create the swapfile using dd

Use the dd command to create a swapfile of the desired size. For example:

sudo dd if=/dev/zero of=/swapfile bs=1M count=1024

Explanation:

  • if=/dev/zero: Input file is a stream of zero bytes.
  • of=/swapfile: Output file is the swapfile to be created.
  • bs=1M: Block size is 1 megabyte.
  • count=1024: Number of blocks to write (1024 blocks of 1 MB = 1 GB).

Set the correct permissions

Restrict access to the swapfile for security:

sudo chmod 600 /swapfile

Format the file as swap

Prepare the file to be used as swap space:

sudo mkswap /swapfile

Enable the swapfile

Activate the swapfile:

sudo swapon /swapfile

Make the swapfile permanent

Add the swapfile entry to the fstab file:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Make sure to check this line wan't there already, or you are mounting a swap partition

How much swap to add

Acording to the ubutu faq

RAMNo HibernationWith HibernationMaximum
256MB256MB512MB512MB
512MB512MB1024MB1024MB
1024MB1024MB2048MB2048MB
1GB1GB2GB2GB
2GB1GB3GB4GB
3GB2GB5GB6GB
4GB2GB6GB8GB
5GB2GB7GB10GB
6GB2GB8GB12GB
8GB3GB11GB16GB
12GB3GB15GB24GB
16GB4GB20GB32GB
24GB5GB29GB48GB
32GB6GB38GB64GB
64GB8GB72GB128GB
128GB11GB139GB256GB
256GB16GB272GB512GB
512GB23GB535GB1TB
1TB32GB1056GB2TB
2TB46GB2094GB4TB
4TB64GB4160GB8TB
8TB91GB8283GB16TB