These ares the steps to create a swap on a file:
Create a large file e.g. with
sudo mkdir -p /var/cache/swap/ # create a directory that holds the swap file
sudo dd if=/dev/zero of=/var/cache/swap/myswap bs=1M count=4096 # for 4 GByte
Of course any other method of creating a file of defined size would do.
Announce swap to the system
sudo chmod 0600 /var/cache/swap/myswap # only root should have access
sudo mkswap /var/cache/swap/myswap # format as swap
sudo swapon /var/cache/swap/myswap # announce to system
Insert the following line in
/etc/fstab for swap from the next boot:
/var/cache/swap/myswap none swap sw 0 0
Note: In case you have your system files on a SSD you may want to consider to hold your swap file on a hard disk location.
Also note: You can not use a swap file for hibernation (see Ubuntu SwapFaq)
Additional note for Ubuntu >= 17.04: A swap on file
/swapfile is created by default in a new installation (when no swap partition was present). We can manually create a swap partition later if we prefer.
In case we want to replace an existing swap (e.g. partition) with another swap (e.g. on file) we need to remove the old swap with
sudo swapoff -a # for all
Then remove the swap entry from
/etc/fstab or replace it with the new swap respectively.