In Linux, swap space is used when the system starts running out of physical memory (RAM). In that case, any inactive data stored in RAM are moved into the swap space, freeing up physical memory for other uses. Swap is also used during hibernation, where all data in RAM are copied to swap, just before powering off the computer.
It is almost always a good idea to have some disk space allocated as swap, but how much swap space is needed depends on your particular circumstances. You can find some example scenarios here.
Sometimes the swap space can be on a separate disk partition, however recent versions of Linux distributions, including Ubuntu, use a special swap file in the root partition as swap space.
Find swap file location
Typically, a swap file should have been created during installation. We can find where that file is located, using the
swapon --show NAME TYPE SIZE USED PRIO /swap.img file 8G 7.3M -2
If for some reason you don’t have any swap space allocated,
swapon shouldn’t show any output, in which case feel free to create a new file.
Create a new swap file
- Deactivate the existing swap file. Obviously, skip this step if you are creating a swap file for the first time.
sudo swapoff /swap.img
- Create an empty file with a size of
8G(8GB) - update this value as required. Run
man fallocatefor more information on how to use this command.
sudo fallocate -l 8G /swap.img
- Format the file as swap space.
sudo mkswap /swap.img
- Activate the new swap file.
sudo swapon /swap.img
Confirm swap file activated
You can use
free to confirm that the new swap file has been activated.
free -h total used free shared buff/cache available Mem: 15Gi 5.4Gi 3.3Gi 250Mi 7.4Gi 10Gi Swap: 8.0Gi 7.2Mi 8.0Gi